Javascript: Implementing setInterval using SetTimeout
In JavaScript timing events come in two flavors:
- setTimeout(function, milliseconds)
Executes a function, after waiting a specified number of milliseconds. - setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
Here is a code to implement setInterval code using setTimeout, also we have a method to clear the interval.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function cstmSetInterval(fn,ms){ var id = setTimeout(function(){ if(typeof fn === 'function'){ fn(); }else{ throw new Error("Expecting a function as input parameter"); } cstmSetInterval(fn,ms); },ms); //consoling out the setTimeout ID console.log(id); } function clearCstmInterval(id){ //clearTimeout takes the id of setTimeout and clears the time event clearTimeout(id); } |
“Keep Learning.”
-Rushi
-Rushi
CobNinja
This is pretty good, but It would be better if Id was stored using ‘this’ context, and clearCstmInterval was returned from the function.