You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.

The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

Tip: 1000 ms = 1 second.

Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.


Function Proto-type

setInterval(function, milliseconds, param1, param2, ...)


Below code shows a number and increase its value every 1 second.

<script type="text/javascript">
var myCount=0;

function increaseNum() {
    myCount++;
    document.getElementById("num").innerHTML = myCount.toString();
}

setInterval(increaseNum, 1000);
</script>

<div id="num">0</div>


Below code shows a table changing its cell with number and color by the defined interval.

<html>
<script type="text/javascript">
var myCnt=0;
var myColor=[ "#ef3fef","#ef6fef","#fefe2e","#fefe4e","#ef9f9f","#ef9f3f","#fe3f3f","#7e3f3f","lightgreen","lightgray","pink","cyan","yellow"];
var clrCnt=myColor.length;

var blockCnt=0;
function drawBody() {
    var sBody="<table border=1>";
    for(i=0; i<10; i++) {
        sBody += "<tr>";
        for( j=0; j<10; j++) {
            sBody += "<td width=70 height=70 id='block" + blockCnt.toString() + "' align=center>0</td>";
            blockCnt++;
        }
        sBody += "</tr>";
    }
    sBody += "</table>";
    document.body.innerHTML = sBody;
}

function alertFunc() {
    myCnt++;
    tmpColor = Math.floor(Math.random()*clrCnt);
    tmpBlock = Math.floor(Math.random()*blockCnt);
    document.getElementById( "block" + tmpBlock).style.backgroundColor  = myColor[tmpColor];
    document.getElementById( "block" + tmpBlock).innerHTML = "<font color=-2>" + myCnt + "</font>";
}

</script>
<!-- Update HTML body when page is loading" -->
<body onLoad="javascript:drawBody();">
</body>
<script type="text/javascript">
    // Launch Timer
    setInterval(alertFunc, 200);
</script>
</html>


  • No labels