cashier-ipad/commons/utils/timer.js

55 lines
1.4 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 任务执行器
*
* @author terrfly
* @site https://www.jeepay.vip
* @date 2022/11/15 16:30
*/
const model = {
// 任务启动工具, 每 xxs调用一次 知道多次x次为止。
// 注意: 启动后将立马调用一次, 而不是1s后再调用。
// 参数:
// allCount: 全部的次数 支持promise 并不一定是 秒)
// stepSecond 步伐(单位: 秒)
// callbackFunc 回调函数, 支持返回 boolean 或者 promise ,
// 注意: boolean类型 true 进入下一次循环, false: 停止任务。
// promise类型 then 进入下一次循环, catch 停止任务。
startTimeoutTask: (stepSecond, allCount, callbackFunc) => {
// 不存在回调函数
if(!callbackFunc){
return false;
}
let callbackResult = callbackFunc(allCount)
// 明确返回false, 说明不再循环
if(callbackResult === false){
return false
}
// 不包含剩余次数了。
if(allCount <= 0){
return false
}
// promise
if(typeof callbackResult == 'object'){
callbackResult.then(() => {
setTimeout(() => model.startTimeoutTask(stepSecond, --allCount, callbackFunc), (stepSecond * 1000) )
})
}else{ // 其他boolean类型 或返回不明确, 继续下一次任务。
setTimeout(() => model.startTimeoutTask(stepSecond, --allCount, callbackFunc), (stepSecond * 1000) )
}
}
}
export default model