<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
<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