How to execute code by timer

The window object has methods, that allows to execute code by timer.

// windows. can be omitted
// out "Hello world!" in console after two seconds
setTimeout(()=>console.log("Hello world!"), 2000);

// show alert after 10 seconds
var timeoutID = setTimeout(window.alert, 10000, 'Delayed alert.');

// you can cancel the timer task
if(cond){
   clearTimeout(timeoutID);
}
methods description
setTimeout(func [, delay] [,arg1, ...argn ) Executes a function once the timer expires.
  • func - a function to be executed after the timer expires
  • delay - the time, in milliseconds, the timer should wait before the specified function or code is executed. If this argument is omitted, a value of 0 is used.
  • argn - argument for function func
clearTimeout( timeoutID) Cancels a timeout previously established by calling setTimeout().
  • timeoutID - The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to setTimeout()
setInterval(func [, delay] [,arg1, ...argn ) Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
  • func - a function to be executed after the timer expires
  • delay - interval, in milliseconds
  • argn - argument for function func
clearInterval( intervalID) Cancels a timed, repeating action which was previously established by a call to setInterval().
  • intervalID - The identifier of the repeated action you want to cancel.