We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
let t = 5 const timer = setInterval(() => { if (--t < 0) clearInterval(timer) }, 1000)
原理是倒计时前记录当前时间 t1,递归时记录递归次数 c1,每一次递归时,用当前时间 t2 - (t1 + c1 * interval) 得到是误差时间 offset,使用 interval - offset 即可得到下一个 setTimeout 的时间。
const t1 = Date.now() let c1 = 0 // 递归次数 let timer: any = null // 计时器 let t = 5 // 倒计时秒数 let interval = 1000 // 间隔 function countDown() { if (--t < 0) { clearTimeout(timer) return } // 计算误差 const offset = Date.now() - (t1 + c1 * interval) const nextTime = interval - offset c1++ timer = setTimeout(countDown, nextTime) } countDown()
The text was updated successfully, but these errors were encountered:
No branches or pull requests
最简单的倒计时秒杀
setTimeout递归
原理是倒计时前记录当前时间 t1,递归时记录递归次数 c1,每一次递归时,用当前时间 t2 - (t1 + c1 * interval) 得到是误差时间 offset,使用 interval - offset 即可得到下一个 setTimeout 的时间。
The text was updated successfully, but these errors were encountered: