Set Interval - Set Timeout

This first example is using setInterval() to run 4 functions in sequence every 2 seconds.

Stop Interval Restart Interval

<script type="text/javascript">
intervalFunctions=4 // number of functions

intervalCount=1
function setIntervalDemo(){
window["myFunction"+intervalCount+"a"]()

if(intervalCount<intervalFunctions){intervalCount++}
else{intervalCount=1}

}

intervalTimer=setInterval("setIntervalDemo()",2*1000)

function myFunction1a(){document.getElementById("d1").innerHTML="Function "+intervalCount}
function myFunction2a(){document.getElementById("d1").innerHTML="Function "+intervalCount}
function myFunction3a(){document.getElementById("d1").innerHTML="Function "+intervalCount}
function myFunction4a(){document.getElementById("d1").innerHTML="Function "+intervalCount}

// add onload=" setIntervalDemo()" to the opening body tag

</script>

<div id="d1"></div>

This second example is using setTimeout() to run 4 functions in sequence every 3 seconds

Stop Timeout Restart Timeout

<script type="text/javascript">
timeoutFunctions=4 // number of functions

timeoutCount=1
function setTimeoutDemo(){
window["myFunction"+timeoutCount+"b"]()

if(timeoutCount<intervalFunctions){timeoutCount++}
else{timeoutCount=1}

timeoutTimer=setTimeout("setTimeoutDemo()",2*1000)

}

function myFunction1b(){document.getElementById("d2").innerHTML="Function "+timeoutCount}
function myFunction2b(){document.getElementById("d2").innerHTML="Function "+timeoutCount}
function myFunction3b(){document.getElementById("d2").innerHTML="Function "+timeoutCount}
function myFunction4b(){document.getElementById("d2").innerHTML="Function "+timeoutCount}

// add onload="setTimeoutDemo()" to the opening body tag

</script>

<div id="d2"></div>

Both setInterval() and setTimeout() are used to do something after a set time but each one does it in different way, in the two examples above the setInterval() timer does not have to be in the function whereas the setTimeout() timer does.

The setInterval() timer simply runs the function every 3 seconds but the setTimeout() timer has to be in the function

interval_Id = setInterval(expression, time)
Continues to call the function at the specified interval

clearInterval(interval_Id)
Cancels the specified timer

setTimeout(expression, time)
Runs once at the specified interval

clearTimeout(timeout_Id)
Cancels the specified timer