Use setInterval()
or setTimeout()
to set a timer. But you should notice a subtle difference between these 2 functions due to single threaded nature of javascript. Let's look at the example:
setTimeout(function test() {
//your code
setTimeout(test, 100);
}, 100);
setInterval(function() {
//your code
}, 100);
These 2 blocks of code appear to be the same, but that's not the case due to single-threaded nature of javascript.
With setInterval()
: if your code is busy executing and takes long time to complete. The next intervals may fire while your code is still executing and these intervals will be queued up. In the end, you may end up with some handlers running in succession without any delay
With setTimeout()
: the next interval is only set to be fired when you're current code has finished. This guarantee that the next execution will never be less than the interval (100 in this case), only equal to or longer.