Skip to content

timerWithControl

Functions

timerWithControl()

timerWithControl(callback, options): Object

创建可控的定时器

注意:不支持自动执行回调,需手动调用 start()flush() 执行回调!

Parameters

ParameterTypeDescription
callbackNoopFn回调句柄
optionsTimerWithControlOptions配置项

Returns

Object

flush

flush: () => void

Returns

void

isActive

isActive: () => boolean

Returns

boolean

start

start: () => void

Returns

void

stop

stop: (cleanup) => void

Parameters
ParameterTypeDefault value
cleanupbooleanfalse
Returns

void

Example

ts
const timer = timerWithControl(() => {
  console.log(Date.now())
})

// 启动定时器
timer.start()

// 停止定时器
timer.stop()

// 停止定时器并立即执行回调
timer.flush()

Interfaces

TimerWithControlOptions

Properties

PropertyTypeDescription
immediateCallback?boolean启动定时器时立即执行一次回调

Default
false
ms?MaybeFn<number>延迟时间,单位:ms,小于等于 0 时不会开启定时器,若 timerType='requestAnimation',则此参数无效

Default
0
onCleanup?() => void-
type?"setTimeout" | "setInterval" | "requestAnimationFrame"定时器类型
- setTimeout: 仅执行一次回调
- setInterval: 循环执行回调,直到手动调用 stop()
- requestAnimationFrame: 循环执行回调,直到手动调用 stop(),非客户端环境时降级为 setTimeout(fn, 16)

Default
'setTimeout'