11import debounce from 'lodash/debounce' ;
22import throttle from 'lodash/throttle' ;
3- import { nextTick , Ref , ref } from 'vue' ;
3+ import { computed , nextTick , Ref , ref } from 'vue' ;
44import { Config } from './config' ;
55import { Queries } from './useAsyncQuery' ;
66import {
@@ -78,7 +78,7 @@ const createQuery = <R, P extends unknown[]>(
7878 onError,
7979 } = config ;
8080
81- let retriedCount = 0 ;
81+ const retriedCount = ref ( 0 ) ;
8282 const loading = ref ( initialState ?. loading ?? false ) ;
8383 const data = ref ( initialState ?. data ?? initialData ) as Ref < R > ;
8484 const error = ref ( initialState ?. error ) ;
@@ -96,7 +96,7 @@ const createQuery = <R, P extends unknown[]>(
9696
9797 // reset retried count
9898 const resetRetriedCount = ( ) => {
99- retriedCount = 0 ;
99+ retriedCount . value = 0 ;
100100 } ;
101101
102102 const count = ref ( 0 ) ;
@@ -154,15 +154,29 @@ const createQuery = <R, P extends unknown[]>(
154154 return ( ) => timerId && clearTimeout ( timerId ) ;
155155 } ;
156156
157+ const actualErrorRetryInterval = computed ( ( ) => {
158+ if ( errorRetryInterval ) return errorRetryInterval ;
159+ const baseTime = 1000 ;
160+ const minCoefficient = 1 ;
161+ const maxCoefficient = 9 ;
162+ // When retrying for the first time, in order to avoid the coefficient being 0
163+ // so replace 0 with 2, the coefficient range will become 1 - 2
164+ const coefficient = Math . floor (
165+ Math . random ( ) * 2 ** Math . min ( retriedCount . value , maxCoefficient ) +
166+ minCoefficient ,
167+ ) ;
168+ return baseTime * coefficient ;
169+ } ) ;
170+
157171 const errorRetryHooks = ( retryFunc : ( ) => void ) => {
158172 let timerId : number ;
159173 const isInfiniteRetry = errorRetryCount === - 1 ;
160- const hasRetryCount = retriedCount < errorRetryCount ;
174+ const hasRetryCount = retriedCount . value < errorRetryCount ;
161175
162176 // if errorRetryCount is -1, it will retry the request until it success
163177 if ( error . value && ( isInfiniteRetry || hasRetryCount ) ) {
164- if ( ! isInfiniteRetry ) retriedCount += 1 ;
165- timerId = setTimeout ( retryFunc , errorRetryInterval ) ;
178+ if ( ! isInfiniteRetry ) retriedCount . value += 1 ;
179+ timerId = setTimeout ( retryFunc , actualErrorRetryInterval . value ) ;
166180 }
167181 return ( ) => timerId && clearTimeout ( timerId ) ;
168182 } ;
0 commit comments