Last active
August 29, 2015 14:16
-
-
Save davidallsopp/3151dd8508209285d2f1 to your computer and use it in GitHub Desktop.
Repeating a function using setTimeout rather than setInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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