setTimeout is a global built in function in Javascript, counting time in milliseconds before running a function
setTimeout() - syntax:
var Id = setTimeout(
function () //Id - will return a unique identifier
{
//actions to run
}
, time); //time to wait in milliseconds
The oposite function is clearTimeout()
clearTimeout() - syntax:
clearTimeout(Id); // Id - the unique idenftifier of the setTimeout function
Sample application of Timeout
the script for the above application is:
var myTimeoutId = 0 //defined out of the function so it can be used in the cancel function
function runTimeOut(){
var cancelButton = document.getElementById("cancelButton");
var timeMs = parseInt(document.getElementById("timeToWait").value);
cancelButton.disabled = false;
myTimeoutId = setTimeout(function () {
var alertText = "Waited " + timeMs + " seconds."
cancelButton.disabled = true;
alert(alertText);
}, timeMs * 1000);
}
function cancelTimeOut() {
var cancelButton = document.getElementById("cancelButton");
clearTimeout(myTimeoutId);
cancelButton.disabled = true;
}
setInterval()
This will perform an action every x milliseconds, until broken by
clearInterval()
var intervalID = setInterval(
function(){
//actions ;
},time);
clearInterval(intervalID);
Sample application of Interval
var myIntervalID = 0
var counter = 1;
var myLabel = document.getElementById("ivalLabel");
function StartInterval(){ //Run the counter
disabledButtons(1,0,1);
myIntervalID = setInterval(function() {
myLabel.innerHTML = "counting " + counter;
console.log(counter);
counter++;
},1000)
};
function stopInterval() { //Stop the counter
disabledButtons(0,1,0);
clearInterval(myIntervalID);
};
function zeroOutInterval(){ //Zero Out the counter
counter = 0;
myLabel.innerHTML = "Start......";
}
function disabledButtons(start,stop,zero){ //Buttons on-off
var startButton = document.getElementById("startButton");
var stopButton = document.getElementById("stopButton");
var zeroButton = document.getElementById("zeroButton");
startButton.disabled = start;
stopButton.disabled = stop;
zeroButton.disabled = zero;
}
Syncronous vs Asyncronous actions:
setTimeout and setInterval are asyncronous action performed by the web-page. This means then can run as a background probess and will not interfere with the page other events a long and exsusting actions should better run with a setTimeout
function with time 0
a sample of setInterval in action with AJAX, based on the Pets selector,