当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript setTimeout和setInterval 的区别

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 javascript setTimeout和setInterval 的区别


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-10   浏览: 381 ::
收藏到网摘: n/a

window对象有两个主要的定时方法,分别是setTimeout 和 setInteval 他们的语法基本上相同,但是完成的功能取有区别。 setTimeout方法是定时程序,也就是在什么时间以后干什么。干完了就拉倒。
setInterval方法则是表示间隔一定时间反复执行某操作。
  如果用setTimeout实现setInerval的功能,就需要在执行的程序中再定时调用自己才行。如果要清除计数器需要 根据使用的方法不同,调用不同的清除方法:
例如:
tttt=setTimeout('northsnow()',1000);
clearTimeout(tttt);
或者:
tttt=setInterval('northsnow()',1000);
clearInteval(tttt);
举一个例子:
复制代码 代码如下:

<div id="liujincai"></div>
<input type="button" name="start" value="start" onclick='startShow();'>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">
var intvalue=1;
var timer2=null;
function startShow()
{
liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();
timer2=window.setTimeout("startShow()",2000);
}
function stop()
{
window.clearTimeout(timer2);
}
</script>

或者:
复制代码 代码如下:

<div id="liujincai"></div>
<input type="button" name="start" value="start" onclick='timer2=window.setInterval("startShow()",2000);//startShow();'>
<input type="button" name="stop" value="stop" onclick="stop();">
<script language="javascript">
var intvalue=1;
var timer2=null;
function startShow()
{
liujincai.innerHTML=liujincai.innerHTML + " " + (intvalue ++).toString();
}
function stop()
{
window.clearInterval(timer2);
}
</script>