Timers

The setTimeout() function allows invoking a specified function provided in its first argument after a certain amount of time in milliseconds that is passed in its second argument. The return value can be used by clearTimeout() function to cancel the execution of the function registered with setTimeout().

let timeout;
setTimeout(() => console.log("After 1 sec"), 1000);
setTimeout(() => console.log("After 2 sec"), 2000);
setTimeout(() => clearTimeout(timeout), 3000);
timeout = setTimeout(() => console.log("After 4 sec"), 4000);

The setInterval() function is used to invoke the specified function repeatedly every time the provided number of milliseconds has elapsed. The return value can be used by clearInterval() function to cancel the repeating execution of the function registered with setInterval().

let clock = setInterval(() => {
  console.clear();
  console.log(new Date().toLocaleString());
}, 1000);

setTimeout(() => clearInterval(clock), 5_000);