js中的setInterval和setTimeout使用实例

来源:互联网 发布:java关键字定义常量 编辑:程序博客网 时间:2024/05/29 10:20

<html>

<body>

<div id="content">

<p><strong>setInterval() 定义和用法</strong></p>
<p>setInterval() 方法可按照指定的周期(以毫秒计)来执行函数或表达式。该方法会不停地循环调用函数,直到使用 clearInterval() 明确停止该函数或窗口被关闭。clearInterval() 函数的参数即 setInterval() 返回的 ID 值。</p>
<p><strong>语法</strong></p>
<p>setInterval(code,millisec[,"lang"])<br>code 必需。要调用的函数或要执行的代码串。<br>millisec 必须。周期性执行或调用 code 之间的时间间隔,以毫秒计。</p>
<p><strong>返回值</strong></p>
<p>一个可以传递给 Window.clearInterval() 从而取消对 code 的周期性执行的值。</p>
<p><strong>使用示例:<br><br></strong></p><div class="codetitle"><span><a style="CURSOR: pointer" data="30297" class="copybut" id="copybut30297" onclick="doCopy('code30297')"><u>复制代码</u></a></span> 代码如下:</div><div class="codebody" id="code30297"><br>&lt;html&gt;<br>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;<br>&lt;body&gt;<br>&lt;input type="text" id="clock" size="35" /&gt;<br>&lt;script language=javascript&gt;<br>var int=setInterval("clock()",50);<br>function clock(){<br>&nbsp;var t=new Date();<br>&nbsp;document.getElementById("clock").value=t;<br>}<br>&lt;/script&gt;<br>&lt;/form&gt;<br>&lt;button onclick="window.clearInterval(int)"&gt;<br>停止 interval 事件&lt;/button&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<br></div><p></p>
<p><strong>setTimeout() 定义和用法</strong></p>
<p>setTimeout() 方法用于在指定的毫秒数后调用函数或计算表达式,该方法与 setInterval() 方法不同的是该方法只执行一次。</p>
<p><strong>语法<br><br></strong>setTimeout(code,millisec)<br>code 必需。要调用的函数后要执行的 JavaScript 代码串。<br>millisec 必需。在执行代码前需等待的毫秒数,以毫秒计。</p>
<p><strong>提示:<br></strong>(1)setTimeout() 虽然是只执行一次代码。但如果许要多次调用,除了使用 setInterval() 外还可以让被执行的代码里面自身再次调用 setTimeout() 方法已达到多次执行的目的。<br>(2)另外setTimeout()方法也同样可以返回一个ID值,以方便使用clearInterval()方法对使用setTimeout()方法的取消。</p>
<p><strong>使用示例:<br><br></strong></p><div class="codetitle"><span><a style="CURSOR: pointer" data="22011" class="copybut" id="copybut22011" onclick="doCopy('code22011')"><u>复制代码</u></a></span> 代码如下:</div><div class="codebody" id="code22011"><br>&lt;html&gt;<br>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;<br>&lt;head&gt;<br>&lt;script type="text/javascript"&gt;<br>function timedMsg(){<br>&nbsp;var t=setTimeout("alert('3 秒时间到!')",3000);<br>}<br>function timedMsgAways(){<br>&nbsp;alert('3 秒时间到!');<br>&nbsp;var t=setTimeout("timedMsgAways()",3000);<br>}<br>&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>&lt;form&gt;<br>&lt;input type="button" value="3 秒后警告" onClick="timedMsg()"&gt;&lt;br /&gt;<br>&lt;input type="button" value="循环 3 秒警告" onClick="timedMsgAways()"&gt;<br>&lt;/form&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;<p></p>
<p></p></div><p></p>
<p>对于这两个方法,需要注意的是如果要求在每隔一个固定的时间间隔后就精确地执行某动作,那么最好使用setInterval,而如果不想由于连续调用产生互相干扰的问题,尤其是每次函数的调用需要繁重的计算以及很长的处理时间,那么最好使用setTimeout。</p>


</div>

</body>

</html>

原创粉丝点击