Last active
December 6, 2024 14:35
-
-
Save AndersDJohnson/4385908 to your computer and use it in GitHub Desktop.
A synchronous version of setInterval (functional form). Waits for the interval function to finish before starting the timeout to the next call.
This file contains hidden or 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
var setIntervalSynchronous = function (func, delay) { | |
var intervalFunction, timeoutId, clear; | |
// Call to clear the interval. | |
clear = function () { | |
clearTimeout(timeoutId); | |
}; | |
intervalFunction = function () { | |
func(); | |
timeoutId = setTimeout(intervalFunction, delay); | |
} | |
// Delay start. | |
timeoutId = setTimeout(intervalFunction, delay); | |
// You should capture the returned function for clearing. | |
return clear; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you so much for this! really needed it
I modified the function slightly to:
clear()
function from inside the callback functionfunc
func
if it's an async function. Without theawait
statement, the next setTimeout will be set without waiting for the first function execution to finish first.Below is my modified version:
Now doing
should be possible