setTimeout()和setInterval()两个方法都是JavaScript的计时事件
相同
1.两者都为HTML DOM Window对象的两个方法
使用可以写成
window.setTimeout();
window.setInterval();
当然不加window也是可以的。
2.两者都有两个参数
setTimeout("javascript function",milliseconds);
setInterval("javascript function",milliseconds);
第一个参数是一个方法
第二个参数是间隔时间(毫秒)
不同
1.
setTimeout();只执行一次,传入一个毫秒数时间到达后执行一次传入function函数,执行完后函数失效。
setInterval(); 循环执行,在传入毫秒间隔时间内循环执行传入function函数,执行后不失效。(clearInterval() 方法用于停止 setInterval() 方法执行的函数代码。 )
实例
实现倒数三秒后跳转当前页面,并在页面显示出倒数。
1.页面
<body style="background-color : #EAEAEA; color :#A3A3A3">
<div>
<span id="totalSecond">3</span>秒后自动返回主页
</div>
</body>
2.JS代码
2.1 setTimeout();实现
function timeout() {
var total = totalSecond.innerText;
if(total <= 0) {
location.href = "http://www.baidu.com";
} else {
totalSecond.innerText = --total;
window.setTimeout("timeout()", 1000);
}
}
window.setTimeout("timeout()", 1000);
2.2 setInterval();实现
function interval() {
var total = totalSecond.innerText;
if(total <= 0) {
location.href = "http://www.baidu.com";
} else {
totalSecond.innerText = --total;
}
}
window.setInterval("interval()", 1000);
注意:
setTimeout和setInterval在页面加载后会自动执行。所以不需要添加document.onload事件。
当然如果两者需要调用function那么调用的function必须要在setTimeout和setInterval代码的前面。
因为js在页面是自上而下运行的,如果放在setTimeout和setInterval的后面则其调用的function为无效方法,程序就会出问题。
如下就是错误的
window.setInterval("interval()", 1000);
function interval() {
var total = totalSecond.innerText;
if(total <= 0) {
location.href = "http://www.baidu.com";
} else {
totalSecond.innerText = --total;
}
}
还有一个三秒后页面跳转的方法,在head标签里添加如下代码,当然页面秒数显示还需要自己添加
<meta http-equiv="Refresh" content="3; url=http://www.baidu.com.cn" />