Sunday, 5 June 2016

javascript - is setInterval more likely to occur on time than continuous setTimeout calls

I have these snippets of code that do the same thing but use different approaches - setInterval and continuous setTimeout calls:




function log() {
console.log('fn')
}

//option 1
var forTimes = 10;
var doneTimes = 0;

var interval = setInterval(function(){
if (doneTimes < forTimes) {

log();
doneTimes++;
} else {
clearInterval(interval);
}
}, 100);

//option 2
function timeoutFn() {
if (doneTimes < forTimes) {

log();
doneTimes++;
setTimeout(timeoutFn, 100);
}
}
setTimeout(timeoutFn, 100);


Because of the nature of single-threaded javascript neither setTimeout nor setInterval guarantees functional call witing 100 ms since thread may be busy running an event handler or doing reflow/repaint. I'm wondering if any of them has higher likelyhood of executing handler within the specified time? If so, why? Does setInterval act like setTimeout in that it waits for the specified interval to pass and only after that adds handler to the queue?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...