One-Off Timers with setTimeout
setTimeout(callback, delay);
Where callback
is a function and delay
is the number of milliseconds until the callback is invoked.
Repeat Timers with setInterval
setInterval(callback, delay);
Where callback
is a function and delay
is the number of milliseconds between each invocation.
NOTE:
setTimeout and setInterval don’t invoke the callback immediately. So, you have to invoke the callback yourself first manually if you want it to run immediately.
Cancel a Timer
Canceling timeouts
const timeoutID = setTimeout(callback, delay);
clearTimeout(timeoutID); //Clears the timeout immediately
Canceling intervals
const intervalID = setInterval(callback, delay);
clearInterval(intervalID); //Clears the interval immediately