Uses setTimeout (fn, 0) to defer code execution until the current call stack is reliable?

I have a function called an unknown number of times. I need to know how many times the function has been run, so I do:

(function () { var i = 0, increment = function () { if (i === 0) { setTimeout(function () { console.log('increment was called ' + i + ' times.'); // increment was called 3 times. i = 0; }, 0); } i++; }; increment(); increment(); increment(); })(); 

Can someone tell me if this is reliable in all browsers or is there a better template for this?

+4
source share
2 answers

setTimeout() puts a function in a queue that runs when all other functions are started.

If you call setTimeout() several times before calling increment() , you will probably notice that the variable i reaches a value greater than 1.

+1
source

Yes, this piece of code seems reliable in all browsers even in the lowest version of IE. I tried this in IE8, I work well.

0
source

All Articles