JavaScript timers

这篇翻译不完整。请帮忙从英语翻译这篇文章

取消一段JavaScript代码通常都是同步执行的,但是一些原生的JavaScript函数(如timers)却允许我们推迟任意指令的执行:

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

Documentation

setTimeout()
在一定的延时后执行一个函数或者一段代码。
setInterval()
在一定的延时后重复执行一个函数或一段代码,每次执行函数的间隔时间为定长。
setImmediate()
当浏览器完成其他操作(如事件和展示等)后,立即执行一个函数。
clearTimeout()
清除由 setTimeout() 所设置的延时。
clearInterval()
取消使用由 setInterval()所设置的操作。
clearImmediate()
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()
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.
performance.now()

performance.now() 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.

Date.now()
Date.now() 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.
Timer.jsm
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,