chuangte_bike_newxcx/pages/index/utils/asyncUtil.js
2026-05-21 09:43:14 +08:00

36 lines
863 B
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.

/**
* 首页蓝牙连接等流程用到的轻量异步工具(与组件内同名方法行为一致)
*/
export function sleep(ms = 300) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* @param {() => boolean} checker
* @param {number} timeout 总超时 ms
* @param {number} interval 轮询间隔 ms
* @returns {Promise<boolean>} 条件在超时前成立为 true否则 false
*/
export function waitForCondition(checker, timeout = 12000, interval = 250) {
return new Promise((resolve) => {
const start = Date.now()
const timer = setInterval(() => {
try {
if (checker()) {
clearInterval(timer)
resolve(true)
return
}
} catch (e) {
clearInterval(timer)
resolve(false)
return
}
if (Date.now() - start >= timeout) {
clearInterval(timer)
resolve(false)
}
}, interval)
})
}