JavaScript defines setTimeout() and setInterval() functions;
these functions are not standard, but are implemented by both browsers and server-side JavaScript engines
The setTimeout function
setTimeout() invokes a function after a specified number of milliseconds has elapsed
timeoutID = setTimeout(function[, delay]);
- the
functionparameter specifies the function to be executed after the timer expires - the
delayparameter specifies the interval, in milliseconds, after the timer expires - the
arg1, arg2, ...optional parameters specify additional arguments passed tofunctionwhen timer expires - the
timeoutIDreturned value identifies the timer; pass this value to theclearTimeout()function to cancel the timeout - note: if
delayparameter is omitted, the function will be called as soon as possible, when the JavaScript engine is idle - note: the
setTimeoutfunction returns immediately and does not wait for the interval to elapse before returning
Example: setTimeout invocations
setTimeout(() => { console.log("Three"); }, 1000);
setTimeout(() => { console.log("two"); }, 2000);
setTimeout(() => { console.log("one"); }, 3000);
setTimeout(() => { console.log("go!"); }, 4000);
Example: using setTimeout() and clearTimeout() with Console API
HTML
<button id="setTmr"> SET Timer </button> <button id="cancelTmr"> CANCEL Timer </button>
JavaScript
let timeoutID;
const create = (e) => {
timeoutID = setTimeout(console.log, 2000, 'Hurry up!');
};
const dismiss = (e) => {
clearTimeout(timeoutID);
};
document.getElementById('setTmr').addEventListener('click', create);
document.getElementById('cancelTmr').addEventListener('click', dismiss);
The setInterval function
The setInterval() invokes a function repeatedly every time a specified number of milliseconds has elapsed
intervalID = setInterval(function[, delay [, arg1, arg2, ...]]);
- the
functionparameter is the function to be executed every interval of time - the
delayparameter is the interval, in milliseconds, the timer should wait for between executions - the
arg1, arg2, ...optional parameters specify additional arguments passed tofunctionwhen timer expires - the returned
intervalIDis a value which identifies the timer; pass this value toclearInterval()to cancel the interval
Example: using setInterval(), and clearInterval()
with Console API
let counter = 0;
let string = "Hello-World";
// every second clear console and log the string
let intervalID = setInterval(() => {
console.clear();
console.log(string.substring(0, ++counter));
if(counter === string.length)
clearInterval(intervalID);
}, 1000);
No comments:
Post a Comment