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

Use recursive setTimeout in place of setInterval #188

Open
schontz opened this issue Jun 22, 2023 · 2 comments
Open

Use recursive setTimeout in place of setInterval #188

schontz opened this issue Jun 22, 2023 · 2 comments

Comments

@schontz
Copy link

schontz commented Jun 22, 2023

setInterval is known to create a backlog of tasks if the run loop gets busy. Why not to use setInterval highlights the issue. Consider using a recursive setTimeout instead.

@kibertoad
Copy link
Owner

@schontz PR would be welcome!

@schontz
Copy link
Author

schontz commented Jun 23, 2023

Something like this:

function setIntervalSafe(fn, ms) {
  let timer;
  const wrapper = (isSetup) => {
    if (!isSetup) fn();
    timer = setTimeout(wrapper, ms);
  }
  wrapper(true);
  return () => clearTimeout(timer);
}

const stopInterval = setIntervalSafe(() => console.log(Date.now()), 1000);
// ...
stopInterval();

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