المعرفة:: JavaScript الحالة::مؤرشفة المراجع:: The Complete JavaScript Course 2022 From Zero to Expert, setInterval, setTimeout, clearInterval, clearTimeout
There are two types of timers in JavaScript:
setTimeout
setTimeout
: sets a timer which executes a function or specified piece of code once the timer expires.- Syntax is
setTimeout(functionRef, delay, param1, param2, /* ... ,*/ paramN)
. delay
parameter is the time in milliseconds that the timer should wait before the specified function or code is executed.- Additional arguments can be passed through
setTimeout
to the function. setTimeout
is non blocking, the code will continue to execute.
clearTimeout(timeoutID)
method cancels a timeout previously established by callingsetTimeout()
.timeoutID
The identifier of the timeout you want to cancel. This ID was returned by the corresponding call tosetTimeout()
.
setInterval
setInterval
: repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.- The syntax is similar to
setTimeout
:setInterval(func, delay, arg0, arg1, /* ... ,*/ argN)
. clearInterval(intervalID)
method cancels a timed, repeating action which was previously established by a call tosetInterval()
.
Note on cancelling intervals and timeouts
It’s worth noting that the pool of IDs used by setInterval()
and setTimeout()
are shared, which means you can technically use clearInterval()
and clearTimeout()
interchangeably. However, for clarity, you should avoid doing so.