I’ve got a function that is called an unknown number of times. I need to know how many times the function was run so I’m doing:
(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 anyone tell me whether this is reliable across all browsers or whether there’s a better pattern to achieve this?
setTimeout()places a function on the queue, which is executed when all the other functions have been run.If you call
setTimeout()a few times before callingincrement(), you will probably notice theivariable reaching a value greater than 1.