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

setTimeout准时 #167

Open
Sunny-117 opened this issue Nov 3, 2022 · 1 comment
Open

setTimeout准时 #167

Sunny-117 opened this issue Nov 3, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@awspi
Copy link

awspi commented Feb 1, 2023

function setTimeoutWithOffset(fn, interval, ...args) {
  let startTime = Date.now()
  let count = 0// 执行次数
  let timer = null
  const task = () => {
    // offset = timeNow - (startTime + count * interval)
    const offset = Date.now() - (startTime + count * interval)
    console.log(`第${count + 1}次 系统延迟时间${offset}`)//
    timer = setTimeout(() => {
      fn.apply(this, args);
      count++
      task();
    }, interval - offset);
  };
  task();
  return () => clearTimeout(timer);
}

//TEST
const stop = setTimeoutWithOffset(() => console.log(123), 1000)
setTimeout(() => {
  stop()
}, 5000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants