当前位置: 首页 > 网络学院 > 客户端脚本教程 > JavaScript > JS Timing
With JavaScript, it is possible to execute some code NOT immediately after a function is called, but after a specified time interval. This is called timing events.
使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做时间事件。
Simple timing[简单的时间事件]
Another simple timing[另一个简单的时间事件]
Timing event in an infinite loop[无限循环的时间事件]
Timing event in an infinite loop - with a Stop button[有停止按钮的无限循环时间事件]
A clock created with a timing event[一个用时间事件建立的时钟]
With JavaScript, it is possible to execute some code NOT immediately after a function is called, but after a specified time interval. This is called timing events.
使用JS是可以让函数不直接执行的,而是在过了一个指定的时间间隔后才执行。这就叫做时间事件。
It's very easy to time events in JavaScript. The two key methods that are used are:
JS的时间事件是非常简单的。使用了两个关键的方法:
Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window object.
注意:setTimeout() 和 Timeout() 都是HTML DOM Window 对象的方法。
var t=setTimeout("javascript statement",milliseconds) |
The setTimeout() method returns a value - In the statement above, the value is stored in a variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable name.
setTimeout()方法返回一个值 - 在上面的声明里,值被保存在变量t中。如果你想取消这个setTimeout()可以使用变量名来提出它(用clearTimeout(t))
The first parameter of setTimeout() is a string that contains a JavaScript statement. This statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".
setTomeout()的第一个参数是字符串声明。它可以像"alert('5 seconds!')"或是调用一个函数像"alertMsg()"
The second parameter indicates how many milliseconds from now you want to execute the first parameter.
第二个参数用来表明从现在开始你希望在多少毫秒后执行第一个参数
Note: There are 1000 milliseconds in one second.
1000毫秒为一秒
When the button is clicked in the example below, an alert box will be displayed after 5 seconds.
当下面的按钮被点击后,每过5秒就会出现一个警告框。
<html> <body> |
To get a timer to work in an infinite loop, we must write a function that calls itself. In the example below, when the button is clicked, the input field will start to count (for ever), starting at 0:
要得到一个无限循环的记时器,我们必须写出一个自我调用的函数。下面的例子,当按钮按下后,输入框就会从0开始记数(永远的)
<html> <body> </html> |
clearTimeout(setTimeout_variable) |
The example below is the same as the "Infinite Loop" example above. The only difference is that we have now added a "Stop Count!" button that stops the timer:
下面的例子和上面的“无限循环”差不多。唯一的不同就是我们现在多了一个“停止记数”的按钮来停止记时器。
<html> function timedCount() function stopCount() <body> </html> |