欢迎来到福编程网,本站提供各种互联网专业知识!

JS Timing

发布时间:2007-04-21 作者: 来源:转载
使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做事件事件。WithJavaScript,itispossibletoexecutesomecodeNOTimmediatelyafterafunctioniscalled,butafteraspecifiedtimeinterval.Thisiscalledtimingevents.使用JS是可

使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做事件事件。
WithJavaScript,itispossibletoexecutesomecodeNOTimmediatelyafterafunctioniscalled,butafteraspecifiedtimeinterval.Thisiscalledtimingevents.
使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做事件事件。
JavaScriptTimingEvents
JS时间事件
WithJavaScript,itispossibletoexecutesomecodeNOTimmediatelyafterafunctioniscalled,butafteraspecifiedtimeinterval.Thisiscalledtimingevents.
使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做事件事件。
It'sveryeasytotimeeventsinJavaScript.Thetwokeymethodsthatareusedare:
JS的时间事件是非常简单的。使用了两个关键的方法:
*setTimeout()-executesacodesometimeinthefuture
在一些时间后执行代码
*clearTimeout()-cancelsthesetTimeout()
取消setTimeout()
Note:ThesetTimeout()andclearTimeout()arebothmethodsoftheHTMLDOMWindowobject.
注意:setTimeout()和Timeout()都是HTMLDOMWindow对象的方法。
setTimeout()
Syntax语法
vart=setTimeout("javascriptstatement",milliseconds)
ThesetTimeout()methodreturnsavalue-Inthestatementabove,thevalueisstoredinavariablecalledt.IfyouwanttocancelthissetTimeout(),youcanrefertoitusingthevariablename.
setTimeout()方法返回一个值-在上面的声明里,值被保存在变量t中。如果你想取消这个setTimeout()可以使用变量名来提出它(用clearTimeout(t))
ThefirstparameterofsetTimeout()isastringthatcontainsaJavaScriptstatement.Thisstatementcouldbeastatementlike"alert('5seconds!')"oracalltoafunction,like"alertMsg()".
setTomeout()的第一个参数是字符串声明。它可以像"alert('5seconds!')"或是调用一个函数像"alertMsg()"
Thesecondparameterindicateshowmanymillisecondsfromnowyouwanttoexecutethefirstparameter.
第二个参数用来表明从现在开始你希望在多少毫秒后执行第一个参数
Note:Thereare1000millisecondsinonesecond.
1000毫秒为一秒
Example
举例
Whenthebuttonisclickedintheexamplebelow,analertboxwillbedisplayedafter5seconds.
当下面的按钮被点击后,每过5秒就会出现一个警告框。



functiontimedMsg()
{
vart=setTimeout("alert('5seconds!')",5000)
}




onClick="timedMsg()">



Example-InfiniteLoop
无限循环
Togetatimertoworkinaninfiniteloop,wemustwriteafunctionthatcallsitself.Intheexamplebelow,whenthebuttonisclicked,theinputfieldwillstarttocount(forever),startingat0:
要得到一个无限循环的记时器,我们必须写出一个自我调用的函数。下面的例子,当按钮按下后,输入框就会从0开始记数(永远的)



varc=0
vart
functiontimedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}




onClick="timedCount()">




clearTimeout()
Syntax语法
clearTimeout(setTimeout_variable)
Example
举例
Theexamplebelowisthesameasthe"InfiniteLoop"exampleabove.Theonlydifferenceisthatwehavenowaddeda"StopCount!"buttonthatstopsthetimer:
下面的例子和上面的“无限循环”差不多。唯一的不同就是我们现在多了一个“停止记数”的按钮来停止记时器。



varc=0
vart
functiontimedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
functionstopCount()
{
clearTimeout(t)
}




onClick="timedCount()">

onClick="stopCount()">


相关推荐