js定时器

来源:互联网 发布:nfs windows 外网 编辑:程序博客网 时间:2024/06/07 02:53

js定时器 - setInterval() 与 setTimeout()


JS有两种定时器方法:

  • 循环定时器setInterval():按指定的周期(以毫秒计算)来调用函数或计算表达式。方法不断的调用函数,直到调用clearInterval()函数被调用或窗口被关闭;
  • 倒计时定时器setTimeout():在指定的毫秒数后调用函数或计算表达式。

setInterval()方法:


语法:setInterval(code,millisec,lang)

描述code必须,要调用的函数或要执行的代码串millisec必须,周期性执行或调用code之间的时间间隔,以毫秒计算lang可选,JScript   |  VBScript  | JavaScript


每1000毫秒执行clock()函数实例,包含停止执行的按钮(1000毫秒 = 1秒)

<html><body><input type="text" id="clock" /><script type="text/javascript">var int=self.setInterval("clock()",1000);function clock(){var d=new Date();var t=d.toLocaleTimeString();document.getElementById("clock").value=t;}</script><button onclick="int=window.clearInterval(int)">停止</button></body></html>

setTimeout()方法

语法:setTimeout(code,millisec,lang)

参数:

code 必需。要调用的函数后执行的javascript代码串
millisec 必需。在执行代码前需等待的毫秒数
lang 可选。脚本语言可以是JScript | VBScript | JavaScript

实例:

<!DOCTYPE html><html><head><meta charset="utf-8"><title>教程实例</title></head><body><p>点击按钮,在等待 3 秒后弹出 "Hello"。</p><button onclick="myFunction()">点我</button><script>function myFunction(){    setTimeout(function(){alert("Hello")},3000);}</script></body></html>

clearTimeout(对象)  清除已设置的setTimeout对象
clearInterval(对象) 清楚已设置的setInterval对象

倒计时定时跳转实例:
<html><head>  <base href="<%=basePath%>">  <title>My JSP 'ds04.jsp' starting page</title>  <span id="tiao">3</span>  <a href="javascript:countDown"> </a>秒后自动跳转……  <meta http-equiv=refresh content=3;url= '/ds02.jsp'/>  <!--脚本开始-->  <script language="javascript" type="">function countDown(secs){ tiao.innerText=secs; if(--secs>0)  setTimeout("countDown("+secs+")",1000); } countDown(3); </script>  <!--脚本结束--> </head>



原创粉丝点击