Heim  >  Artikel  >  Web-Frontend  >  javascript计时器事件使用详解_基础知识

javascript计时器事件使用详解_基础知识

WBOY
WBOYOriginal
2016-05-16 17:04:531032Durchsuche

在 JavaScritp 中使用计时事件是很容易的,两个关键方法是:

setTimeout()
未来的某时执行代码

clearTimeout()
取消setTimeout()
setTimeout()
语法

复制代码 代码如下:

var t=setTimeout("javascript语句",毫秒)


setTimeout() 方法会返回某个值。在上面的语句中,值被储存在名为 t 的变量中。假如你希望取消这个 setTimeout(),你可以使用这个变量名来指定它。
setTimeout() 的第一个参数是含有 JavaScript 语句的字符串。这个语句可能诸如 "alert('5 seconds!')",或者对函数的调用,诸如 alertMsg()"。

第二个参数指示从当前起多少毫秒后执行第一个参数。

提示:1000 毫秒等于一秒。

当下面这个例子中的按钮被点击时,一个提示框会在5秒中后弹出。

复制代码 代码如下:










实例 - 无穷循环

要创建一个运行于无穷循环中的计时器,我们需要编写一个函数来调用其自身。在下面的例子中,当按钮被点击后,输入域便从 0 开始计数。

复制代码 代码如下:











clearTimeout()

语法

复制代码 代码如下:

clearTimeout(setTimeout_variable)
 

实例

下面的例子和上面的无穷循环的例子相似。唯一的不同是,现在我们添加了一个 "Stop Count!" 按钮来停止这个计数器:

复制代码 代码如下:













另外两个重要的方法:
复制代码 代码如下:

setInterval()
setInterval() - executes a function, over and over again, at specified time intervals

作用是:循环执行一个方法,在规定的间隔时间内

语法:

复制代码 代码如下:

window.setInterval("javascript function",milliseconds);

说明:第一个参数必须是一个函数,第二个参数是执行函数的间隔时间.

实例:

复制代码 代码如下:




说明:上面例子,执行效果是说每隔500ms就alert("hello");

再来一个时钟:

复制代码 代码如下:






    

如何停止,setInterval()方法??

复制代码 代码如下:

window.clearInterval()

语法:
复制代码 代码如下:

window.clearInterval(intervalVariable)


复制代码 代码如下:

The window.clearInterval() method can be written without the window prefix.

To be able to use the clearInterval() method, you must use a global variable when creating the interval method:

myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.

实例:

复制代码 代码如下:




stop




}

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn