To stop and clear the instance of running Javascript setTimeout timer clearTimeout is used. clearTimeout stops the timer started by setTimeout function of Javascript.
JavaScript clearTimeout syntax
clearTimeout (TimerID);
JavaScript cleatTimeout function takes 1 parameter:
TimerID: timer id of the timer instance initiated by setTimeout function.
setTimeout method returns the timerID when it is executed in javascript code.
Example of JavaScript clearTimeout with setTimeout function
var timeOut;
function startTimer()
{
document.getElementById('myTime').innerHTML = Date();
timeOut = setTimeout("startTimer();",1000);
}
function stopTimer()
{
clearTimeout(timeOut);
}
In the above example HTML Div element is used to display the output. In Javascript code 1 variable is declared to store the setTimeout timerID. startTimer function has setTimeout function that calls startTimer function after every 1000 milliseconds and the timeout variable stores the timerID returned by the setTimeout method.
JavaScript code in the above example has timeout variable declared globally at the top so that it could be accessed by all the functions any time. In stopTimer function clearTimeout method is used to cancel the setTimeout by passing the stored timerID in timeout variable.
Continue to next tutorial: JavaScript setInterval to learn how to set the timer interval to execute the JavaScript function after equal intervals of time.