The setTimeout() and setInterval() methods allows to schedule timer-based callbacks in JavaScript
setTimeout()
Executes a callback function after a specified number of milliseconds.
Javascript setTimeout takes 2 parameters, one is Callback function and then the delay in Milliseconds.
The syntax is:
var timerId = setTimeout(callback, delay)setTimeout() Example:
function foo() {
alert('Hi')
}
setTimeout(foo, 1000);
We can also Cancel the execution of the setTimeout in JavaScript.
To Cancel the Execution we need to store the value returned by setTimeout and then call clearTimeout().
Example below for Cancelling the Clear timeout.
function foo() {
alert('Hi');
}
var timeID = setTimeout(foo, 1000);
clearTimeout(timeID);
setInterval()
Executes a callback function at specified time intervals.
The syntax is:
var timerId = setInterval(callback, interval);setInterval() Example:
function foo() {
alert('Hi');
}
setInterval(foo, 1000);
For setTimeout() we have cancel function clearTimeout(). for setInterval() also we have Cancel function available clearInterval().
Same like setTimeout(), to Cancel the Execution of setInterval(), we need to store the value returned by setInterval and then call setInterval().
Example below for Cancelling the Clear timeout.
function foo() {
alert('Hi');
}
var timeID = setInterval(foo, 1000);
clearInterval(timeID);
No comments:
Post a Comment