setTimeout与setInterval的区别:
1、setTimeout设置后隔指定时间后只会执行一次
2、setInterval设置后会每隔指定时间执行一次
3、setTimeout一般在方法内部使用达到循环调用的效果
4、setInterval一般在方法外部使用就可以达到循环调用效果
setTimeout例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" language="javascript">
var timeout;
//显示时间
function displayTime(){
var date = new Date();
var hour = date.getHours();
hour = hour<10?"0"+hour:hour;
var minute = date.getMinutes();
minute = minute<10?"0"+minute:minute;
var second = date.getSeconds();
second = second<10?"0"+second:second;
//将时、分、秒组成时间
var time = hour+":"+minute+":"+second;
//将时间显示在文本框中
document.getElementById("txtTime").value = time;
//参数一:要调用的函数 参数二:延迟时间 返回值:Timeout对象
timeout = window.setTimeout("displayTime()",1000);
}
function stopTime(){
window.clearTimeout(timeout);//清除Timeout对象
}
function continueTime(){
timeout = window.setTimeout("displayTime()",1000);
}
</script>
</head>
<body onload="displayTime()">
<input type="text" id="txtTime" />
<input type="button" onclick="stopTime()" value="停止" />
<input type="button" onclick="continueTime()" value="继续" />
</body>
</html>
setInterval例子;
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript" language="javascript">
var timeout;
//显示时间
function displayTime(){
var date = new Date();
var hour = date.getHours();
hour = hour<10?"0"+hour:hour;
var minute = date.getMinutes();
minute = minute<10?"0"+minute:minute;
var second = date.getSeconds();
second = second<10?"0"+second:second;
//将时、分、秒组成时间
var time = hour+":"+minute+":"+second;
//将时间显示在文本框中
document.getElementById("txtTime").value = time;
}
function stopTime(){
window.clearTimeout(timeout);//清除Timeout对象
}
function continueTime(){
timeout = window.setInterval("displayTime()",1000);
}
timeout = window.setInterval("displayTime()",1000);
//window.onload窗体加载事件,后面接的函数不能加左右小括号
//window.onload = displayTime();//不会调用函数,会没效果
window.onload = displayTime;//正确
</script>
</head>
<body>
<input type="text" id="txtTime" />
<input type="button" onclick="stopTime()" value="停止" />
<input type="button" onclick="continueTime()" value="继续" />
</body>
</html>