Use the setInterval method to implement loop calling functions at specified intervals until the clearInterval method cancels the loop.
When canceling the loop with the clearInterval method, the call of the setInterval method must be assigned to a variable, and the clearInterval method then references the variable.
The code copy is as follows:
<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>
Use setTimeout and clearTimeout to complete the delay call, run the specified function after the specified delay time, and execute it only once. The usage of clearTimeout is the same as that of clearInterval.
The code copy is as follows:
<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+"year"+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>