Timers
The browser’s internal timer-scheduler makes it possible to delay a function call for some time. There are timeouts and intervals for this that control when and how often the function is called. Timers are built into browsers, not into the language, and are available on the global window
object.
Timeout
The setTimeout()
method serves to schedule a function to run after a specific time.
const timerId = setTimeout(callback, delay, arg1, arg2, ...);
callback
: a function to be scheduled.delay
: time in milliseconds after which the callback function is called once.
Additional arguments (arg1
, arg2
, etc.) will be passed to the callback when calling. It returns the numeric identifier of the created timer, which is used to delete it. .
If, for some reason, you need to cancel a function call inside a timeout, the clearTimeout(id)
method should be used, which takes a timer identifier and clears (deletes) it.
const greet = () => {
console.log("Hello!");
};
const timerId = setTimeout(greet, 3000);
clearTimeout(timerId);
Since you have called clearTimeout()
, which will be executed before the greet()
function is called, the timer with timerId
will be deleted and the delayed greet()
call will be unregistered. Therefore, nothing will be displayed in the console.
Interval
The setInterval()
method is a simple way of repeating code over and over again at a specified repetition interval. The syntax and parameters are the same as for setTimeout()
. Unlike setTimeout()
, the interval starts the execution of a function not once, but regularly repeats it after the specified interval. You can stop execution by calling the clearInterval(id)
method.
const timerId = setInterval(callback, delay, arg1, arg2, ...);
Click the "Start" button to start the interval and output a string to the console every second. Use Math.random()
to make the strings different. By clicking the "Stop" button, call clearInterval()
and pass the identifier of the interval to be stopped.
Counter frequency
The browser timer has the minimum delay value. In modern browsers, it ranges from around 0
to 4
milliseconds. In older browsers, the delay can be longer, up to 15
milliseconds. According to the standard, the minimum delay is 4
milliseconds, so there is no difference between setTimeout(callback, 1)
and setTimeout(callback, 4)
.
The timer may fire less often than specified in the delay
parameter, because if the processor load is too high, some starts of interval functions will be skipped. Browsers continue to execute timeouts and intervals even when the browser tab is inactive, but they reduce the timer frequency.