Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Last active August 29, 2015 14:16
Show Gist options
  • Save davidallsopp/3151dd8508209285d2f1 to your computer and use it in GitHub Desktop.
Save davidallsopp/3151dd8508209285d2f1 to your computer and use it in GitHub Desktop.
Repeating a function using setTimeout rather than setInterval
// Poll repeatedly. Use setTimeout rather than setInterval
// to ensure previous execution has completed before enqueing a new one
(function repeat() {
do_something();
setTimeout(repeat, 2000);
})();
// The repeat function's scope is limited, so one can have multiple blocks like this
// without them interfering - and can wrap this in a helper function in the style of
// setInterval:
function setSafeInterval(callback, millis) {
(function repeat() {
callback();
setTimeout(repeat, millis);
})();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment