Skip to content

d3-timer

该模块提供了一个高效的队列,能够管理数千个并发动画,同时保证与并发或分阶段动画的一致、同步的时序。在内部,如果可用,它使用 requestAnimationFrame 实现流畅动画,对于超过 24 毫秒的延迟,则切换到 setTimeout

🌐 This module provides an efficient queue capable of managing thousands of concurrent animations, while guaranteeing consistent, synchronized timing with concurrent or staged animations. Internally, it uses requestAnimationFrame for fluid animation (if available), switching to setTimeout for delays longer than 24ms.

现在()

🌐 now()

来源 · 如果可用,则返回由 performance.now 定义的当前时间;如果不可用,则返回 Date.now 的时间。

js
d3.now() // 1236.3000000715256

当前时间在一帧开始时更新;因此在这一帧期间是保持一致的,并且在同一帧期间安排的任何计时器都会同步。如果该方法在帧之外被调用,例如响应用户事件时,当前时间会被计算出来,然后固定直到下一帧,再次确保事件处理期间的时间一致性。

🌐 The current time is updated at the start of a frame; it is thus consistent during the frame, and any timers scheduled during the same frame will be synchronized. If this method is called outside of a frame, such as in response to a user event, the current time is calculated and then fixed until the next frame, again ensuring consistent timing during event handling.

timer(callback, delay, time)

来源 · 调度一个新的定时器,重复调用指定的 callback,直到定时器被 停止。可以选择指定一个以毫秒为单位的数字 delay,以在延迟之后调用给定的 callback;如果未指定 delay,则默认为零。延迟是相对于指定的以毫秒为单位的 time;如果未指定 time,则默认为 现在

回调函数将接收到自定时器激活以来的(表观)已经过的时间。例如:

🌐 The callback is passed the (apparent) elapsed time since the timer became active. For example:

js
const t = d3.timer((elapsed) => {
  console.log(elapsed);
  if (elapsed > 200) t.stop();
}, 150);

这将大致产生以下控制台输出:

🌐 This produces roughly the following console output:

3
25
48
65
85
106
125
146
167
189
209

(具体数值可能会根据你的 JavaScript 运行环境以及电脑正在进行的其他操作而有所不同。)注意,第一个经过的时间是 3 毫秒:这是从计时器开始算起的经过时间,而不是从计时器被调度时开始计算的时间。由于指定了延迟,这里计时器在调度后 150 毫秒才开始。如果页面在后台且 requestAnimationFrame 被暂停,表观的经过时间可能小于实际经过时间;在后台时,表观时间会被冻结。

如果在另一个定时器的回调中调用 timer,新的定时器回调(如果根据指定的 delaytime 符合条件)将在当前帧结束时立即被调用,而不是等到下一帧。在一个帧内,定时器回调保证按它们被调度的顺序调用,而不管它们的开始时间。

🌐 If timer is called within the callback of another timer, the new timer callback (if eligible as determined by the specified delay and time) will be invoked immediately at the end of the current frame, rather than waiting until the next frame. Within a frame, timer callbacks are guaranteed to be invoked in the order they were scheduled, regardless of their start time.

timer.restart(callback, delay, time)

来源 · 使用指定的回调以及可选的延迟时间重新启动计时器。这相当于停止此计时器并使用指定的参数创建一个新的计时器,尽管此计时器保留了原始的调用优先级。

timer.stop()

来源 · 停止此计时器,防止后续的回调。如果计时器已经停止,此方法无效。

timerFlush()

来源 · 立即调用任何符合条件的定时器回调。请注意,零延迟定时器通常会在一帧之后(约17毫秒)首次执行。这可能会导致短暂的闪烁,因为浏览器会渲染页面两次:一次在第一个事件循环结束时,另一次立即在第一个定时器回调时。通过在第一个事件循环结束时刷新定时器队列,你可以立即运行任何零延迟定时器,从而避免闪烁。

timeout(callback, delay, time)

来源 · 类似于 timer,但计时器在其第一次回调时会自动 停止。是 setTimeout 的一个合适替代,保证不会在后台运行。回调函数会被传入经过的时间。

interval(callback, delay, time)

Source · 类似于 timer,不同之处在于 callback 只在每个 delay 毫秒时被调用一次;如果未指定 delay,则等同于 timer。这是 setInterval 的合适替代方案,保证不会在后台运行。callback 会接收经过的时间作为参数。