白日梦之流口水

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

      在web开发中,经常会用到javascript,并且也很经常需要在一定的时间间隔内重复执行一个代码或函数。一般我都会用 setTimeout 这个方法。
今天在翻阅DOM帮助手册时无意中看到这个方法:setInterval 。很惊喜,因为我发现在某些情况下使用 setInterval 要比 setTimeout 优越很多。

setInterval Method

Syntax

iTimerID = window.setInterval(vCode, iMilliSeconds [, sLanguage])

Parameters

vCode Required. Variant that specifies a function pointer or string that indicates the code to be executed when the specified interval has elapsed.
iMilliSeconds Required. Integer that specifies the number of milliseconds.
sLanguage Optional. String that specifies any one of the possible values for the LANGUAGE attribute.

Return Value

Integer. Returns an identifier that cancels the timer with the clearInterval method.

setTimeout Method

Syntax

iTimerID = window.setTimeout(vCode, iMilliSeconds [, sLanguage])

Parameters

vCode Required. Variant that specifies the function pointer or string that indicates the code to be executed when the specified interval has elapsed.
iMilliSeconds Required. Integer that specifies the number of milliseconds.
sLanguage Optional. String that specifies one of the following values:
JScript Language is JScript.
VBScript Language is VBScript.
JavaScript Language is JavaScript.

Return Value

Integer. Returns an identifier that cancels the evaluation with the clearTimeout method.


我以为 setInterval 比 setTimeout 好用的地方在:当我们需要重复执行一段代码时,直接用setInterval 在设定的时间间隔后就会循环执行。而setTimeout要实现这个目标,就需要在执行函数里加入setTimeout每执行完一遍代码就要重新申请一个setTimeout,因为它只在设定时间时执行一次code,然后当前这个setTimeout就失效了。这样当逻辑复杂后,循环控制将变得很困难。而现在有了setInterval就可以轻易的解决掉这个问题。setInterval 会在每个设定时间时执行一遍code。
posted on 2007-05-25 00:11  阿钢  阅读(322)  评论(0)    收藏  举报