I created a function to understand the behavior of the setTimeout() function in javascript. I created a recursive function which keeps calling itself. It worked fine until I added a sleep function inside. Here's the code.
'use strict';
(function iterate(i) {
var t=setTimeout(function () {
console.log('timeout ' + i + ' ' + (new Date()));
sleep(1000);
console.log('timeout ' + i + ' ' + (new Date()));
//clearTimeout(t);
iterate(++i);
},2000);
})(0);
function sleep(millis) {
console.log('sleeping...');
var date = new Date();
var curDate = null;
do {
curDate = new Date();
}
while (curDate - date < millis);
}
Here's the output when I run this code.
timeout 0 Wed May 13 2015 12:07:21 GMT+0530 (IST)
sleeping...
timeout 0 Wed May 13 2015 12:07:22 GMT+0530 (IST)
timeout 1 Wed May 13 2015 12:07:25 GMT+0530 (IST)
sleeping...
timeout 1 Wed May 13 2015 12:07:26 GMT+0530 (IST)
timeout 2 Wed May 13 2015 12:07:29 GMT+0530 (IST)
sleeping...
timeout 2 Wed May 13 2015 12:07:30 GMT+0530 (IST)
The difference between two iterate calls should be 2 seconds but it is always sleep_time + delay_time, which in this case is 3 seconds. Also adding clearTimeout() just before calling iterate(), makes it work normal.
Can anyone explain what is happening here?