javascript 定时器

  • setTimeout()--用于指定在一段特定的时间后执行某段程序。

          格式:

[定时器对象名=]setTimeout(“<表达式>”,毫秒数);

功能: 执行<表达式>一次。

其中表达式是字符串,可以使任意javascript语句

<html> 
<head> 

<script type="text/javascript"> 
//5秒之后执行alert 
function count(){ 
    setTimeout("alert('执行成功');",5000); 
}

</script> 

</head>

<body> 
<input type="button" value="执行" onclick="count()"> 
</body> 
</html>

 

  • setInterval()—重复执行<表达式>,直至窗口、框架被关闭或执行clearInterval

格式: [定时器对象名=]setInterval(“<表达式>”,毫秒)

 

clearInterval() 终止定时器

格式: clearInterval(定时器对象名)

 

<html> 
<head> 

<script type="text/javascript"> 
var sec=0; 
var timeId=setInterval("count();",1000);


function count(){ 
    document.getElementById("num").innerHTML=sec++; 
}


function stopCount(){ 
    clearInterval(timeId); 
} 
</script> 

</head>

<body> 
<font style="color:red" id="num">0</font>秒钟<input type="button" value="停止" onclick="stopCount();"> 
</body> 
</html>
原文地址:https://www.cnblogs.com/qq-757617012/p/4179195.html