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.
|
clearTimeout( timeoutID) | Cancels a timeout previously established by calling 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().
|
clearInterval( intervalID) | Cancels a timed, repeating action which was previously established by a call to setInterval().
|