SetInterval和设定延时函数setTimeout的使用和取消

1,095 阅读2分钟
使用
SetInterval和设定延时函数setTimeout 很类似。setTimeout 运用在延迟一段时间,再进行某项操作。
setTimeout("function",time) 设置一个超时对象 setInterval("function",time) 设置一个超时对象
SetInterval为自动重复,setTimeout不会重复。
clearTimeout(对象) 清除已设置的setTimeout对象 clearInterval(对象) 清除已设置的setInterval对象
使用定时器实现
JavaScript的延期执行或重复执行 window对象提供了两个方法来实现定时器的效果,分别是window.setTimeout()和window.setInterval。其中前者可以使一段代码在指定时间后运行;而后者则可以使一段代码每过指定时间就运行一次。它们的原型如下: window.setTimeout(expression,milliseconds); window.setInterval(expression,milliseconds); 其中,expression可以是用引号括起来的一段代码,也可以是一个函数名,到了指定的时间,系统便会自动调用该函数,当使用函数名作为调用句柄时,不能带有任何参数;而使用字符串时,则可以在其中写入要传递的参数。两个方法的第二个参数是milliseconds,表示延时或者重复执行的毫秒数。
1.1window.setTimeout方法
<
html xmlns
=
"http://www.w3.org/1999/xhtml" lang
=
"en"
>
<
head
>
<
meta http-equiv
=
"Content-Type" content
=
"text/html; charset=UTF-8" />
<
title>setTimout_SetInterval</title
>
</head
>
<
script type
=
"text/javascript"
>
function helloWorld() {
alert("helloWorld");
}
window.setTimeout(helloWorld, 5000);
</script
>
<
body
>
</body
>
</html
>
1.2
在延时期限到达之前取消延执行
:
window.clearTimeout(timeoutId)
<
html xmlns
=
"http://www.w3.org/1999/xhtml" lang
=
"en"
>
<
head
>
<
meta http-equiv
=
"Content-Type" content
=
"text/html; charset=UTF-8" />
<
title>setTimout_SetInterval</title
>
</head
>
<
script type
=
"text/javascript"
>
function helloWorld() {
alert("helloWorld");
}
//
window.setTimeout(helloWorld, 5000);
var hw = window.setTimeout(helloWorld, 5000);
document
.
onclick = function() {
alert("取消helloWorld()");
window.clearTimeout(hw);
}
</script
>
<
body
>
</body
>
</html
>
2.1window.setInterval()方法
<
html xmlns
=
"http://www.w3.org/1999/xhtml" lang
=
"en"
>
<
head
>
<
meta http-equiv
=
"Content-Type" content
=
"text/html; charset=UTF-8" />
<
title>setTimout_SetInterval</title
>
</head
>
<
script type
=
"text/javascript"
>
function helloWorld() {
alert("helloWorld");
}
window.setInterval(helloWorld, 3000);
</script
>
<
body
>
</body
>
</html
>
2.2
window.setInterval方法 该方法使得一个函数每隔固定时间被调用一次,是一个很常用的方法。如果想要取消定时执行,和clearTimeout方法类似,可以调用window.clearInterval方法。clearInterval方法同样接收一个setInterval方法返回的值作为参数。
<
html xmlns
=
"http://www.w3.org/1999/xhtml" lang
=
"en"
>
<
head
>
<
meta http-equiv
=
"Content-Type" content
=
"text/html; charset=UTF-8" />
<
title>setTimout_SetInterval</title
>
</head
>
<
script type
=
"text/javascript"
>
function helloWorld() {
alert("helloWorld");
}
//window.setInterval(helloWorld, 3000);
var hw = window.setInterval(helloWorld, 1000);
document
.
onclick = function() {
alert("取消helloWorld()");
window.clearTimeout(hw);
}
</script
>
<
body
>
</body
>
</html
>

更多技术资讯可关注:gzitcast