Brief analysis of javascript interval call and delay call

  • 2020-03-30 04:15:59
  • OfStack

With the setInterval method, you can loop through the function at a specified interval until the clearInterval method cancels the loop

When the loop is cancelled with the clearInterval method, the call to the setInterval method must be assigned to a variable, which is then referenced by the clearInterval method.


<script type="text/javascript">
    var n = 0;
    function print(){
        document.writeln(n);
       
        if(n==1000){
        window.clearInterval(s);
        }   
        n++;
    }
     var s = window.setInterval(print, 10);
</script>

Complete the delay call with setTimeout and clearTimeout, running the specified function after the specified delay time, only once. The use of clearTimeout is the same as the use of the clearInterval method.


<script type="text/javascript">
    function printTime(){
        var time = new Date();
        var year = time.getFullYear();
        var month = (time.getMonth())+1;
        var daynum = time.getDay();
        var hour = time.getHours();
        var min = time.getMinutes();
        var sec = time.getSeconds();
        var da = time.getDate();
        var daystr;
        switch(daynum){
        case 0: daystr=" Sunday ";
            break;
        case 1: daystr=" Monday ";
            break;
        case 2: daystr=" Tuesday ";
            break;
        case 3: daystr=" Wednesday ";
            break;
        case 4: daystr=" Thursday ";
            break;
        case 5: daystr=" Friday ";
            break;
        case 6: daystr=" Saturday ";
            break;
        default: daystr="";
        }
        var str = year+" years "+month+" month "+da+" day   "+daystr+" "+hour+": "+min+": "+sec;
        document.getElementById("t").innerHTML = str;
        window.setTimeout(printTime, 1000);
    }
</script> <body onload="printTime()">
<br/>
<div id="t"></div>
</body>


Related articles: