Skip to content
New issue

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

【JS】实现一个准确的计时器 #105

Open
Easay opened this issue May 27, 2021 · 0 comments
Open

【JS】实现一个准确的计时器 #105

Easay opened this issue May 27, 2021 · 0 comments
Labels

Comments

@Easay
Copy link
Owner

Easay commented May 27, 2021

最简单的倒计时秒杀

let t = 5
const timer = setInterval(() => {
  if (--t < 0) clearInterval(timer)
}, 1000)

setTimeout递归

原理是倒计时前记录当前时间 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()
@Easay Easay added the JS label May 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant