JavaScript timers



setTimeout()方法通常用来在一定时间间隔之后执行一个函数; setInterval() 方法用来在一定的时间间隔下不间断的执行一个函数,例如逐帧动画; The setImmediate()  方法可以用来替代 setTimeout(0) 方法来滞后完成一些需要占用大量cpu时间的操作; requestAnimationFrame() 告诉浏览器你想要执行的动画并且要求浏览器根据自己的频率进行一次重绘。


清除由 setTimeout() 所设置的延时。
取消使用由 setInterval()所设置的操作。
Cancels the immediate actions, just like clearTimeout() for setTimeout().
Using JavaScript timers within animations (Javascript Daemons Management)
In Computer science a daemon is a task that runs as a background process, rather than being under the direct control of an interactive user. In JavaScript programming language, are called daemons all processes created by JavaScript timers or by a Worker instantiation. Here are some code snippets which simplify and abstract the management of daemons.
requestAnimationFrame() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. The method takes as an argument a callback to be invoked before the repaint. returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. This timestamp is equal to the number of milliseconds since the navigationStart attribute of the performance.timing interface. returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Using JavaScript timers within workers
Workers can use timeouts and intervals just like the main thread can. This can be useful, for example, if you want to have your worker thread run code periodically instead of nonstop.
Functions available to workers
In addition to the standard JavaScript set of functions (such as String, Array, Object, JSON etc), there are a variety of functions available from the DOM to workers. This article provides a list of those.
Basic animations
Since we're using script to control canvas elements it's also very easy to make (interactive) animations. Unfortunately the canvas element was never designed to be used in this way (unlike Flash) so there are limitations.
The Timer.jsm JavaScript code module contains pure-JavaScript implementations of setTimeout and clearTimeout that are compatible with the DOM window functions, but that can be used by code that does not have access to a DOM window (for example, JavaScript code modules or content frame scripts).

See also



 此页面的贡献者: monster-gump, xiongwilee, WarriorWu
 最后编辑者: monster-gump,