setInterval, bad!!! This, good.
Using setTimeout to mimic setInterval for recursive JS.
by mayoung
HTML
<h1>setInterval vs setTimeout for recursive JS</h1>
<p>setInterval is generally bad because you have a function being executed at intervals regardless of whether or not the previous call to the function has completed. The setTimeout example below waits for the doStuff function to complete before it moves on. This is a much better way to handle interval timing.</p>
<h2>Counter</h2>
<span id="counter">0</span>
CSS
body {font: 12px/15px arial; margin: 10px;}
h1 {font-size: 1.8em; margin-bottom: 5px;}
h2 {font-size: 1.3em;}
JavaScript
var currentCount = 0;
var doStuff = function(){
var counterSpan = $('#counter');
currentCount = currentCount+1;
counterSpan.html(currentCount);
};
/* setInterval Example
setInterval(function(){
doStuff();
}, 500);
*/
// setTimeout Example
(function loopingFunction() {
doStuff();
setTimeout(loopingFunction, 500);
})();