zl程序教程

您现在的位置是:首页 >  后端

当前栏目

JavaScriptsetTimeout和setInterval的使用方法说明

方法 使用 说明 setInterval
2023-06-13 09:14:17 时间
不同的是setInterval会每隔指定的时间段就执行一次代码,具有重复性。而setTimeout只会调用后执行一次。
下面通过函数的建立和函的自动删除来深刻理解两个函数;
1.函数的建立
setTimeOut的建立:
复制代码代码如下:

showTime();
functionshowTime()
{
vartoday=newDate();
alert("Thetimeis:"+today.toString());
setTimeout("showTime()",5000);
}

调用函数后五秒钟才会执行一次showtime函数
setInterval的建立
复制代码代码如下:

setInterval("showTime()",5000);
functionshowTime()
{
vartoday=newDate();
alert("Thetimeis:"+today.toString());
}

总结:貌似两个函数的结果相似,其实不然第二个函数会反复的报时,直到该网页被关闭。
两个函数的消除:
setTimeout的消除使用
clearTimeout()函数;调用的实例:
复制代码代码如下:
vartimeoutProcess=setTimeout("alert("GOAL!")",3000);
varstopGoalLink=document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink,"click",stopGoal,false);//加入事件函数,参数为(目标;事件;调用的函数;是否冒泡)
functionstopGoal()
{
clearTimeout(timeoutProcess);
}

setInterval的消除
复制代码代码如下:
vartimeoutProcess=setTimeout("alert("GOAL!")",3000);
varstopGoalLink=document.getElementById("stopGoalLink");
attachEventListener(stopGoalLink,"click",stopGoal,false);//加入事件函数,参数为(目标;事件;调用的函数;是否冒泡)
functionstopGoal()
{
clearInterval(timeoutProcess);
}