time-and-timers

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Time and Timers

时间与计时器

Clock plugin, TimerEvent, delays, loops, Timeline event sequencing, pausing time, time scale, and delta time in Phaser 4.
Key source paths:
src/time/Clock.js
,
src/time/TimerEvent.js
,
src/time/Timeline.js
,
src/time/typedefs/
,
src/time/events/
Related skills: ../scenes/SKILL.md, ../tweens/SKILL.md
Clock插件、TimerEvent、延迟、循环、Timeline事件序列、暂停时间、时间缩放以及Phaser 4中的delta time。
核心源码路径:
src/time/Clock.js
,
src/time/TimerEvent.js
,
src/time/Timeline.js
,
src/time/typedefs/
,
src/time/events/
相关技能: ../scenes/SKILL.md, ../tweens/SKILL.md

Quick Start

快速入门

js
// In a Scene's create() method:

// One-shot delayed call (fires once after 1 second)
this.time.delayedCall(1000, () => {
    console.log('One second later');
});

// Repeating timer (fires 5 times, once every 500ms)
this.time.addEvent({
    delay: 500,
    callback: () => { console.log('tick'); },
    repeat: 4   // 4 repeats = 5 total fires
});

// Infinite loop timer
this.time.addEvent({
    delay: 1000,
    callback: this.spawnEnemy,
    callbackScope: this,
    loop: true
});
this.time
is the scene's
Clock
instance (registered as the
'Clock'
plugin under the key
time
). It creates and manages
TimerEvent
objects that fire callbacks based on game time.
js
// 在场景的create()方法中:

// 一次性延迟调用(1秒后触发一次)
this.time.delayedCall(1000, () => {
    console.log('1秒后触发');
});

// 重复计时器(触发5次,每500ms一次)
this.time.addEvent({
    delay: 500,
    callback: () => { console.log('tick'); },
    repeat: 4   // 4次重复 = 总共触发5次
});

// 无限循环计时器
this.time.addEvent({
    delay: 1000,
    callback: this.spawnEnemy,
    callbackScope: this,
    loop: true
});
this.time
是场景的
Clock
实例(在插件系统中以
time
为键注册为
'Clock'
插件)。它负责创建并管理
TimerEvent
对象,这些对象会根据游戏时间触发回调。

Core Concepts

核心概念

Clock (this.time)

Clock(this.time)

The Clock is a Scene-level plugin that tracks game time and updates all of its TimerEvents each frame. Key properties:
  • now
    -- current time in ms (equivalent to
    time
    passed to the scene
    update
    method).
  • startTime
    -- timestamp when the scene started.
  • timeScale
    -- multiplier applied to delta time. Default
    1
    . Values above 1 speed up all timers; below 1 slow them down;
    0
    freezes time.
  • paused
    -- when
    true
    , no TimerEvents are updated.
The Clock listens to
PRE_UPDATE
(to flush pending additions/removals) and
UPDATE
(to tick active events). It is automatically shut down and destroyed with the scene.
Clock是场景级插件,用于跟踪游戏时间并在每一帧更新所有TimerEvent对象。关键属性:
  • now
    -- 当前时间(毫秒),与传递给场景
    update
    方法的
    time
    参数等效。
  • startTime
    -- 场景启动时的时间戳。
  • timeScale
    -- 应用于delta time的乘数,默认值为
    1
    。大于1的值会加速所有计时器;小于1的值会减慢计时器;
    0
    会冻结时间。
  • paused
    -- 当值为
    true
    时,所有TimerEvent都不会被更新。
Clock会监听
PRE_UPDATE
(用于处理待添加/移除的计时器)和
UPDATE
(用于触发活跃事件)事件。它会随场景自动关闭和销毁。

TimerEvent

TimerEvent

A TimerEvent accumulates elapsed time each frame:
elapsed += delta * clock.timeScale * event.timeScale
. When
elapsed >= delay
, the callback fires. After all repeats are exhausted the event is removed from the Clock on the next frame.
Key properties set via config:
delay
,
repeat
,
loop
,
callback
,
callbackScope
,
args
,
timeScale
,
startAt
,
paused
.
TimerEvent会在每一帧累积经过的时间:
elapsed += delta * clock.timeScale * event.timeScale
。当
elapsed >= delay
时,回调函数会被触发。当所有重复次数耗尽后,事件会在下一帧从Clock中移除。
通过配置项设置的关键属性:
delay
repeat
loop
callback
callbackScope
args
timeScale
startAt
paused

Timeline (this.add.timeline)

Timeline(this.add.timeline)

A Timeline is a sequencer for scheduling actions at specific points in time. Unlike the Clock (which manages independent timers), a Timeline runs a linear sequence of events keyed by absolute or relative timestamps.
js
const timeline = this.add.timeline([
    { at: 0,    run: () => { /* immediate */ } },
    { at: 1000, run: () => { /* at 1s */ } },
    { at: 2500, tween: { targets: sprite, alpha: 0, duration: 500 } }
]);
timeline.play();
Timelines always start paused. You must call
play()
to start them. They are created via the GameObjectFactory and destroyed automatically when the scene shuts down.
Timeline是用于在特定时间点调度动作的序列器。与Clock(管理独立计时器)不同,Timeline会按绝对或相对时间戳执行线性事件序列。
js
const timeline = this.add.timeline([
    { at: 0,    run: () => { /* 立即执行 */ } },
    { at: 1000, run: () => { /* 1秒时执行 */ } },
    { at: 2500, tween: { targets: sprite, alpha: 0, duration: 500 } }
]);
timeline.play();
Timeline创建后默认处于暂停状态,必须调用
play()
才能启动。它通过GameObjectFactory创建,并随场景关闭自动销毁。

Common Patterns

常见模式

Delayed Call

延迟调用

js
// Shorthand -- fires once, no repeat
this.time.delayedCall(2000, () => {
    this.scene.start('GameOver');
});
js
// 简写形式 -- 仅触发一次,无重复
this.time.delayedCall(2000, () => {
    this.scene.start('GameOver');
});

Repeating Timer with Finite Count

有限次数重复计时器

js
// repeat: 9 means 10 total fires (1 initial + 9 repeats)
const timer = this.time.addEvent({
    delay: 200,
    callback: this.fireBullet,
    callbackScope: this,
    repeat: 9
});

// Check progress
timer.getRepeatCount();       // repeats remaining
timer.getOverallProgress();   // 0..1 across all repeats
js
// repeat: 9表示总共触发10次(1次初始触发 + 9次重复)
const timer = this.time.addEvent({
    delay: 200,
    callback: this.fireBullet,
    callbackScope: this,
    repeat: 9
});

// 检查进度
timer.getRepeatCount();       // 剩余重复次数
timer.getOverallProgress();   // 所有重复的整体进度(0到1)

Infinite Loop

无限循环

js
const spawner = this.time.addEvent({
    delay: 3000,
    callback: this.spawnWave,
    callbackScope: this,
    loop: true
});

// Stop it later
spawner.remove();  // or spawner.paused = true to pause
Setting
repeat: -1
is equivalent to
loop: true
.
js
const spawner = this.time.addEvent({
    delay: 3000,
    callback: this.spawnWave,
    callbackScope: this,
    loop: true
});

// 后续停止计时器
spawner.remove();  // 或者设置spawner.paused = true来暂停
设置
repeat: -1
loop: true
效果相同。

First-Fire Shortcut with startAt

使用startAt实现首次快速触发

js
// First fire happens quickly (after 100ms), then every 2s
this.time.addEvent({
    delay: 2000,
    callback: this.heartbeat,
    callbackScope: this,
    loop: true,
    startAt: 1900  // pre-fill elapsed so first fire is at 100ms
});
js
// 首次触发快速执行(100ms后),之后每2秒触发一次
this.time.addEvent({
    delay: 2000,
    callback: this.heartbeat,
    callbackScope: this,
    loop: true,
    startAt: 1900  // 预填充已流逝时间,使首次触发在100ms后执行
});

Stopping and Removing Timers

停止与移除计时器

js
const timer = this.time.addEvent({ delay: 1000, loop: true, callback: fn });

// Option 1: Remove from clock (schedules removal next frame)
timer.remove();            // silently expires
timer.remove(true);        // fires callback one last time, then expires

// Option 2: Remove via Clock
this.time.removeEvent(timer);

// Option 3: Remove all timers
this.time.removeAllEvents();
js
const timer = this.time.addEvent({ delay: 1000, loop: true, callback: fn });

// 方式1:从Clock中移除(安排在下一帧移除)
timer.remove();            // 静默过期
timer.remove(true);        // 最后一次触发回调,然后过期

// 方式2:通过Clock移除
this.time.removeEvent(timer);

// 方式3:移除所有计时器
this.time.removeAllEvents();

Pausing and Resuming

暂停与恢复

js
// Pause the entire Clock (all timers freeze)
this.time.paused = true;
this.time.paused = false;

// Pause a single timer
timer.paused = true;
timer.paused = false;
js
// 暂停整个Clock(所有计时器冻结)
this.time.paused = true;
this.time.paused = false;

// 暂停单个计时器
timer.paused = true;
timer.paused = false;

Time Scale (Slow Motion / Fast Forward)

时间缩放(慢动作/快进)

js
// Slow all timers in this scene to half speed
this.time.timeScale = 0.5;

// Speed up a single timer to 2x
timer.timeScale = 2;

// Combined: effective scale = clock.timeScale * event.timeScale
// So 0.5 * 2 = 1x for that specific timer
js
// 将当前场景中所有计时器速度减慢至一半
this.time.timeScale = 0.5;

// 将单个计时器速度加快至2倍
timer.timeScale = 2;

// 组合效果:实际缩放比例 = clock.timeScale * event.timeScale
// 因此0.5 * 2 = 该计时器的实际速度为1倍

Reading Timer State

读取计时器状态

js
timer.getProgress();              // 0..1 for current iteration
timer.getOverallProgress();       // 0..1 across all repeats
timer.getElapsed();               // ms elapsed this iteration
timer.getElapsedSeconds();        // seconds elapsed this iteration
timer.getRemaining();             // ms until next fire
timer.getRemainingSeconds();      // seconds until next fire
timer.getOverallRemaining();      // ms until final fire
timer.getOverallRemainingSeconds(); // seconds until final fire
timer.getRepeatCount();           // repeats left
js
timer.getProgress();              // 当前迭代的进度(0到1)
timer.getOverallProgress();       // 所有重复的整体进度(0到1)
timer.getElapsed();               // 当前迭代已流逝的毫秒数
timer.getElapsedSeconds();        // 当前迭代已流逝的秒数
timer.getRemaining();             // 距离下次触发的毫秒数
timer.getRemainingSeconds();      // 距离下次触发的秒数
timer.getOverallRemaining();      // 距离最终触发的毫秒数
timer.getOverallRemainingSeconds(); // 距离最终触发的秒数
timer.getRepeatCount();           // 剩余重复次数

Timeline: Sequencing Events

Timeline:事件序列编排

js
const timeline = this.add.timeline([
    {
        at: 0,
        run: () => { this.title.setAlpha(1); },
        sound: 'intro'
    },
    {
        at: 2000,
        tween: { targets: this.title, y: 100, duration: 1000 },
        sound: { key: 'whoosh', config: { volume: 0.5 } }
    },
    {
        at: 4000,
        set: { alpha: 0 },
        target: this.title,
        event: 'INTRO_DONE'
    }
]);

timeline.on('INTRO_DONE', (target) => { /* custom event */ });
timeline.on('complete', (tl) => { /* all events ran */ });
timeline.play();
js
const timeline = this.add.timeline([
    {
        at: 0,
        run: () => { this.title.setAlpha(1); },
        sound: 'intro'
    },
    {
        at: 2000,
        tween: { targets: this.title, y: 100, duration: 1000 },
        sound: { key: 'whoosh', config: { volume: 0.5 } }
    },
    {
        at: 4000,
        set: { alpha: 0 },
        target: this.title,
        event: 'INTRO_DONE'
    }
]);

timeline.on('INTRO_DONE', (target) => { /* 自定义事件处理 */ });
timeline.on('complete', (tl) => { /* 所有事件执行完成 */ });
timeline.play();

Timeline: Relative Timing with
from
and
in

Timeline:使用
from
in
实现相对计时

js
const timeline = this.add.timeline([
    { at: 1000, run: stepOne },         // absolute: 1s from start
    { from: 500, run: stepTwo },        // relative: 500ms after previous (1.5s)
    { from: 1000, run: stepThree }      // relative: 1000ms after previous (2.5s)
]);
  • at
    -- absolute ms from timeline start (default 0).
  • in
    -- offset from current
    elapsed
    time (useful when adding events to a running timeline).
  • from
    -- offset from the previous event's start time.
Priority:
from
overrides
in
, which overrides
at
.
js
const timeline = this.add.timeline([
    { at: 1000, run: stepOne },         // 绝对时间:从开始后1秒
    { from: 500, run: stepTwo },        // 相对时间:上一个事件后500ms(1.5秒时)
    { from: 1000, run: stepThree }      // 相对时间:上一个事件后1000ms(2.5秒时)
]);
  • at
    -- 相对于Timeline启动的绝对毫秒数(默认0)。
  • in
    -- 相对于当前
    elapsed
    时间的偏移量(在运行中的Timeline添加事件时有用)。
  • from
    -- 相对于上一个事件启动时间的偏移量。
优先级:
from
覆盖
in
in
覆盖
at

Timeline: Conditional Events

Timeline:条件事件

js
const timeline = this.add.timeline([
    {
        at: 5000,
        if: () => this.player.health > 0,
        run: () => { this.showBonusRound(); }
    }
]);
If the
if
callback returns
false
, the event is skipped (marked complete but actions are not executed).
js
const timeline = this.add.timeline([
    {
        at: 5000,
        if: () => this.player.health > 0,
        run: () => { this.showBonusRound(); }
    }
]);
如果
if
回调返回
false
,该事件会被跳过(标记为完成但不执行动作)。

Timeline: Looping

Timeline:循环

js
const timeline = this.add.timeline([
    { at: 0, run: () => console.log('start') },
    { at: 1000, run: () => console.log('end') }
]);

timeline.repeat().play();      // infinite loop
timeline.repeat(3).play();     // loop 3 additional times (4 total runs)
timeline.repeat(false).play(); // no looping
The
loop
callback on a TimelineEventConfig fires on repeat iterations (not the first run).
js
const timeline = this.add.timeline([
    { at: 0, run: () => console.log('开始') },
    { at: 1000, run: () => console.log('结束') }
]);

timeline.repeat().play();      // 无限循环
timeline.repeat(3).play();     // 额外循环3次(总共执行4次)
timeline.repeat(false).play(); // 不循环
TimelineEventConfig中的
loop
回调会在重复迭代时触发(首次运行时不会触发)。

Timeline: Pause, Resume, Stop, Reset

Timeline:暂停、恢复、停止、重置

js
timeline.pause();      // freezes elapsed counter and pauses spawned tweens
timeline.resume();     // resumes elapsed counter and unpauses spawned tweens
timeline.stop();       // sets paused=true, complete=true
timeline.reset();      // elapsed=0, all events marked incomplete, starts playing
timeline.isPlaying();  // true if not paused and not complete
timeline.getProgress(); // 0..1 based on events completed / total events
js
timeline.pause();      // 冻结已流逝时间计数器并暂停生成的补间
timeline.resume();     // 恢复已流逝时间计数器并恢复生成的补间
timeline.stop();       // 设置paused=true,complete=true
timeline.reset();      // elapsed=0,所有事件标记为未完成,开始播放
timeline.isPlaying();  // 如果未暂停且未完成则返回true
timeline.getProgress(); // 根据已完成事件数/总事件数返回0到1的进度值

Timeline: Time Scale

Timeline:时间缩放

js
timeline.timeScale = 2;   // double speed
timeline.timeScale = 0.5; // half speed
Note: Timeline
timeScale
does not affect tweens created by the timeline. Set tween timeScale separately.
js
timeline.timeScale = 2;   // 速度加倍
timeline.timeScale = 0.5; // 速度减半
注意:Timeline的
timeScale
不会影响其创建的补间。需单独设置补间的timeScale,或使用TweenManager。

Timeline: Full Cutscene Example

Timeline:完整过场动画示例

Timelines excel at choreographing cutscenes with mixed actions (callbacks, tweens, sounds, property sets, and custom events):
js
class CutsceneScene extends Phaser.Scene {
    create() {
        const timeline = this.add.timeline([
            {
                at: 0,
                run: () => { console.log('Start!'); }
            },
            {
                at: 1000,
                tween: {
                    targets: this.player,
                    x: 400,
                    duration: 500,
                    ease: 'Power2'
                }
            },
            {
                at: 1500,
                sound: 'doorOpen'
            },
            {
                at: 2000,
                set: { visible: true },
                target: this.door
            },
            {
                from: 500,
                run: () => { console.log('Relative timing'); }
            },
            {
                at: 5000,
                event: 'cutsceneDone',
                stop: true
            }
        ]);

        timeline.on('cutsceneDone', () => {
            this.scene.start('GameScene');
        });

        timeline.play();
    }
}
Timeline擅长编排包含多种动作(回调、补间、音效、属性设置和自定义事件)的过场动画:
js
class CutsceneScene extends Phaser.Scene {
    create() {
        const timeline = this.add.timeline([
            {
                at: 0,
                run: () => { console.log('开始!'); }
            },
            {
                at: 1000,
                tween: {
                    targets: this.player,
                    x: 400,
                    duration: 500,
                    ease: 'Power2'
                }
            },
            {
                at: 1500,
                sound: 'doorOpen'
            },
            {
                at: 2000,
                set: { visible: true },
                target: this.door
            },
            {
                from: 500,
                run: () => { console.log('相对计时'); }
            },
            {
                at: 5000,
                event: 'cutsceneDone',
                stop: true
            }
        ]);

        timeline.on('cutsceneDone', () => {
            this.scene.start('GameScene');
        });

        timeline.play();
    }
}

Timer Reset and Reuse

计时器重置与复用

A completed
TimerEvent
can be reset with a new config and re-added to the Clock:
js
const timer = this.time.addEvent({
    delay: 1000,
    callback: this.phase1,
    callbackScope: this,
    repeat: 2
});

// Later, after it completes, reconfigure and re-add:
timer.reset({
    delay: 500,
    callback: this.phase2,
    callbackScope: this,
    repeat: 4
});
this.time.addEvent(timer);  // must re-add; reset() alone does not schedule it
已完成的
TimerEvent
可以通过新配置重置并重新添加到Clock:
js
const timer = this.time.addEvent({
    delay: 1000,
    callback: this.phase1,
    callbackScope: this,
    repeat: 2
});

// 后续,完成后重新配置并添加:
timer.reset({
    delay: 500,
    callback: this.phase2,
    callbackScope: this,
    repeat: 4
});
this.time.addEvent(timer);  // 必须重新添加;仅调用reset()不会调度计时器

Configuration Reference

配置参考

TimerEventConfig

TimerEventConfig

PropertyTypeDefaultDescription
delay
number
0
Delay in ms before the callback fires
repeat
number
0
Times to repeat after first fire. Use
-1
for infinite
loop
boolean
false
If
true
, repeats indefinitely (same as
repeat: -1
)
callback
function--Function called when the timer fires
callbackScope
anyTimerEventThe
this
context for the callback
args
Array
[]
Extra arguments passed to the callback
timeScale
number
1
Per-event time multiplier
startAt
number
0
Pre-fill elapsed time in ms (makes first fire happen sooner)
paused
boolean
false
Start the timer in a paused state
属性类型默认值描述
delay
number
0
回调触发前的延迟时间(毫秒)
repeat
number
0
首次触发后的重复次数,使用
-1
表示无限重复
loop
boolean
false
如果为
true
,则无限重复(与
repeat: -1
效果相同)
callback
function--计时器触发时调用的函数
callbackScope
anyTimerEvent回调函数的
this
上下文
args
Array
[]
传递给回调函数的额外参数
timeScale
number
1
单个计时器的时间乘数
startAt
number
0
预填充的已流逝时间(毫秒),使首次触发更快发生
paused
boolean
false
计时器以暂停状态启动

TimelineEventConfig

TimelineEventConfig

PropertyTypeDefaultDescription
at
number
0
Absolute time in ms from timeline start
in
number--Offset from current elapsed (overrides
at
)
from
number--Offset from previous event time (overrides
at
and
in
)
run
function--Callback invoked when event fires
loop
function--Callback invoked on repeat iterations (not first run)
if
function--Guard function; return
false
to skip the event
event
string--Event name emitted on the Timeline instance
target
any--Scope for
run
/
loop
/
if
and target for
set
set
object--Key-value pairs applied to
target
when event fires
tween
TweenConfig--Tween config or instance created when event fires
sound
string/object--Sound key or
{ key, config }
to play
once
boolean
false
Remove this event after it fires
stop
boolean
false
Stop the entire timeline when this event fires
属性类型默认值描述
at
number
0
相对于Timeline启动的绝对时间(毫秒)
in
number--相对于当前已流逝时间的偏移量(覆盖
at
from
number--相对于上一个事件时间的偏移量(覆盖
at
in
run
function--事件触发时调用的回调
loop
function--重复迭代时调用的回调(首次运行时不触发)
if
function--守卫函数;返回
false
则跳过该事件
event
string--在Timeline实例上触发的事件名称
target
any--
run
/
loop
/
if
的上下文,以及
set
的目标对象
set
object--事件触发时应用于
target
的键值对
tween
TweenConfig--事件触发时创建的补间配置或实例
sound
string/object--要播放的音效键或
{ key, config }
对象
once
boolean
false
事件触发后移除该事件
stop
boolean
false
该事件触发时停止整个Timeline

TimelineEvent (Internal)

TimelineEvent(内部)

The processed event object stored in
timeline.events[]
. Extends config with:
PropertyTypeDescription
complete
booleanWhether this event has fired
time
numberResolved absolute time in ms
repeat
numberHow many times this event has repeated
tweenInstance
Tween/TweenChainReference to spawned tween (if any)
存储在
timeline.events[]
中的处理后事件对象,在配置基础上扩展了以下属性:
属性类型描述
complete
boolean该事件是否已触发
time
number解析后的绝对时间(毫秒)
repeat
number该事件已重复的次数
tweenInstance
Tween/TweenChain生成的补间引用(如有)

Events

事件

Timeline Events

Timeline事件

EventConstantListener SignatureFired When
'complete'
Phaser.Time.Events.COMPLETE
(timeline)
All timeline events have been run
Custom events via the
event
property in TimelineEventConfig are also emitted on the Timeline instance with signature
(target)
.
事件常量监听器签名触发时机
'complete'
Phaser.Time.Events.COMPLETE
(timeline)
所有Timeline事件执行完成时
通过TimelineEventConfig中
event
属性定义的自定义事件也会在Timeline实例上触发,签名为
(target)

TimerEvent / Clock

TimerEvent / Clock

TimerEvent and Clock do not emit EventEmitter events. Timers use the
callback
property directly. The Clock is managed by scene lifecycle events (
PRE_UPDATE
,
UPDATE
,
SHUTDOWN
,
DESTROY
).
TimerEvent和Clock不会触发EventEmitter事件。计时器直接使用
callback
属性。Clock由场景生命周期事件(
PRE_UPDATE
UPDATE
SHUTDOWN
DESTROY
)管理。

API Quick Reference

API速查

Clock (this.time)

Clock(this.time)

MethodSignatureReturnsDescription
addEvent
(config | TimerEvent)
TimerEvent
Create and schedule a timer event
delayedCall
(delay, callback, args?, scope?)
TimerEvent
Shorthand for a one-shot delayed call
removeEvent
(event | event[])
this
Remove specific timer(s)
removeAllEvents
()
this
Schedule removal of all active timers
clearPendingEvents
()
this
Clear timers not yet added to active list
PropertyTypeDescription
now
numberCurrent clock time in ms
startTime
numberTime the scene started
timeScale
numberDelta multiplier for all timers
paused
booleanFreeze all timers
方法签名返回值描述
addEvent
(config | TimerEvent)
TimerEvent
创建并调度一个计时器事件
delayedCall
(delay, callback, args?, scope?)
TimerEvent
一次性延迟调用的简写形式
removeEvent
(event | event[])
this
移除指定的一个或多个计时器
removeAllEvents
()
this
安排移除所有活跃计时器
clearPendingEvents
()
this
清除尚未添加到活跃列表的计时器
属性类型描述
now
number当前Clock时间(毫秒)
startTime
number场景启动时间
timeScale
number所有计时器的delta时间乘数
paused
boolean冻结所有计时器

TimerEvent

TimerEvent

MethodReturnsDescription
getProgress()
number0..1 progress of current iteration
getOverallProgress()
number0..1 progress across all repeats
getElapsed()
numberElapsed ms this iteration
getElapsedSeconds()
numberElapsed seconds this iteration
getRemaining()
numberMs until next fire
getRemainingSeconds()
numberSeconds until next fire
getOverallRemaining()
numberMs until final fire
getOverallRemainingSeconds()
numberSeconds until final fire
getRepeatCount()
numberRepeats remaining
remove(dispatchCallback?)
voidExpire the timer (optionally fire callback)
reset(config)
TimerEventReinitialize with new config
destroy()
voidNull out callback references
方法返回值描述
getProgress()
number当前迭代的进度(0到1)
getOverallProgress()
number所有重复的整体进度(0到1)
getElapsed()
number当前迭代已流逝的毫秒数
getElapsedSeconds()
number当前迭代已流逝的秒数
getRemaining()
number距离下次触发的毫秒数
getRemainingSeconds()
number距离下次触发的秒数
getOverallRemaining()
number距离最终触发的毫秒数
getOverallRemainingSeconds()
number距离最终触发的秒数
getRepeatCount()
number剩余重复次数
remove(dispatchCallback?)
void使计时器过期(可选触发回调)
reset(config)
TimerEvent使用新配置重新初始化计时器
destroy()
void清空回调引用

Timeline (this.add.timeline)

Timeline(this.add.timeline)

MethodSignatureReturnsDescription
add
(config | config[])
this
Append events to the timeline
play
(fromStart?)
this
Start playing (default resets to start)
pause
()
this
Pause timeline and spawned tweens
resume
()
this
Resume timeline and spawned tweens
stop
()
this
Stop (sets paused + complete)
reset
(loop?)
this
Reset elapsed and all events to incomplete
repeat
(amount?)
this
Set loop count (-1/true=infinite, false=none)
clear
()
this
Remove all events, reset elapsed, pause
isPlaying
()
booleanTrue if not paused and not complete
getProgress
()
number0..1 based on completed event count
PropertyTypeDescription
elapsed
numberCurrent elapsed time in ms
timeScale
numberDelta multiplier (does not affect spawned tweens)
paused
booleanWhether timeline is paused
complete
booleanWhether all events have run
loop
numberNumber of additional loops (0=none, -1=infinite)
iteration
numberCurrent loop iteration
totalComplete
numberCount of events that have fired
events
TimelineEvent[]The internal event array
方法签名返回值描述
add
(config | config[])
this
向Timeline追加事件
play
(fromStart?)
this
开始播放(默认重置到起始位置)
pause
()
this
暂停Timeline和生成的补间
resume
()
this
恢复Timeline和生成的补间
stop
()
this
停止播放(设置paused和complete为true)
reset
(loop?)
this
重置已流逝时间并将所有事件标记为未完成
repeat
(amount?)
this
设置循环次数(-1/true表示无限,false表示无循环)
clear
()
this
移除所有事件,重置已流逝时间并暂停
isPlaying
()
boolean如果未暂停且未完成则返回true
getProgress
()
number根据已完成事件数/总事件数返回0到1的进度值
属性类型描述
elapsed
number当前已流逝时间(毫秒)
timeScale
numberdelta时间乘数(不影响生成的补间)
paused
booleanTimeline是否处于暂停状态
complete
boolean所有事件是否已执行完成
loop
number额外循环次数(0表示无循环,-1表示无限)
iteration
number当前循环迭代次数
totalComplete
number已触发的事件数量
events
TimelineEvent[]内部事件数组

Gotchas

注意事项

  1. repeat vs total fires.
    repeat: 4
    means 5 total callback invocations (1 initial + 4 repeats). This is a common off-by-one source.
  2. Zero delay with repeat throws. A
    TimerEvent
    with
    delay: 0
    and any repeat/loop will throw
    'TimerEvent infinite loop created via zero delay'
    .
  3. Timelines start paused. You must call
    timeline.play()
    after creation. Forgetting this is a frequent mistake.
  4. Timeline timeScale does not affect tweens. Setting
    timeline.timeScale
    only scales the timeline's own elapsed counter. Tweens created by the timeline run at their own speed. Set tween
    timeScale
    separately or use the TweenManager.
  5. once events are removed permanently. Timeline events with
    once: true
    are spliced out after firing and will not reappear on
    reset()
    or when looping.
  6. Timer additions are deferred.
    addEvent()
    pushes to a pending list processed in
    preUpdate
    . The timer will not be active until the next frame.
  7. Clock paused vs timeScale 0. Both freeze timers, but
    paused = true
    skips the update loop entirely, while
    timeScale = 0
    still runs the loop with zero delta. Prefer
    paused
    for a full freeze.
  8. callbackScope default. If you omit
    callbackScope
    , the TimerEvent itself becomes
    this
    inside the callback, not the scene. Use arrow functions or pass
    callbackScope: this
    explicitly.
  9. Reusing TimerEvent instances. You can pass a
    TimerEvent
    object to
    addEvent()
    , but it must not be in a completed state. The Clock will reset its elapsed and dispatch state.
  10. Timeline
    from
    chains.
    Each
    from
    offset is relative to the previous event's resolved time, not the previous
    from
    value. Events are processed in array order.
  11. Scene pause pauses the Timeline. When a scene is paused (
    scene.pause()
    ), the Timeline's update loop stops too, since Timeline updates are driven by the scene's update step.
  12. timer.reset()
    does not re-add to Clock.
    Calling
    timer.reset(config)
    reinitializes the timer but does not schedule it. You must call
    this.time.addEvent(timer)
    again after resetting.
  1. 重复次数与总触发次数
    repeat: 4
    表示总共触发5次回调(1次初始触发 + 4次重复)。这是常见的差一错误来源。
  2. 零延迟加重复会抛出错误
    delay: 0
    且设置了重复/循环的
    TimerEvent
    会抛出
    'TimerEvent infinite loop created via zero delay'
    错误。
  3. Timeline默认暂停:创建后必须调用
    timeline.play()
    才能启动。忘记这一点是常见错误。
  4. Timeline时间缩放不影响补间:设置
    timeline.timeScale
    仅缩放Timeline自身的已流逝计数器。Timeline创建的补间会以自身速度运行,需单独设置补间的
    timeScale
    或使用TweenManager。
  5. once事件会被永久移除:设置
    once: true
    的Timeline事件触发后会被移除,调用
    reset()
    或循环时不会重新出现。
  6. 计时器添加是延迟处理的
    addEvent()
    会将计时器加入待处理列表,在
    preUpdate
    中处理。计时器要到下一帧才会激活。
  7. Clock暂停与timeScale为0的区别:两者都会冻结计时器,但
    paused = true
    会完全跳过更新循环,而
    timeScale = 0
    仍会运行循环但delta为0。完全冻结时优先使用
    paused
  8. callbackScope默认值:如果省略
    callbackScope
    ,回调函数中的
    this
    会是TimerEvent实例而非场景。请使用箭头函数或显式传递
    callbackScope: this
  9. 复用TimerEvent实例:可以将
    TimerEvent
    对象传递给
    addEvent()
    ,但该对象不能处于已完成状态。Clock会重置其已流逝时间和调度状态。
  10. Timeline的
    from
    链式结构
    :每个
    from
    偏移量是相对于上一个事件的解析时间,而非上一个
    from
    值。事件按数组顺序处理。
  11. 场景暂停会暂停Timeline:当场景暂停(
    scene.pause()
    )时,Timeline的更新循环也会停止,因为Timeline的更新由场景的update步骤驱动。
  12. timer.reset()
    不会重新添加到Clock
    :调用
    timer.reset(config)
    会重新初始化计时器,但不会调度它。重置后必须再次调用
    this.time.addEvent(timer)

Source File Map

源码文件映射

FileDescription
src/time/Clock.js
Scene Clock plugin -- creates, updates, removes TimerEvents
src/time/TimerEvent.js
Individual timer -- delay, repeat, loop, progress tracking
src/time/Timeline.js
Event sequencer -- scheduled actions, tweens, sounds, looping
src/time/typedefs/TimerEventConfig.js
Config typedef for
addEvent()
src/time/typedefs/TimelineEventConfig.js
Config typedef for
timeline.add()
src/time/typedefs/TimelineEvent.js
Internal event object typedef
src/time/events/COMPLETE_EVENT.js
'complete'
event constant for Timeline
src/time/events/index.js
Events namespace barrel file
文件描述
src/time/Clock.js
场景Clock插件 -- 创建、更新、移除TimerEvent
src/time/TimerEvent.js
单个计时器 -- 延迟、重复、循环、进度跟踪
src/time/Timeline.js
事件序列器 -- 调度动作、补间、音效、循环
src/time/typedefs/TimerEventConfig.js
addEvent()
的配置类型定义
src/time/typedefs/TimelineEventConfig.js
timeline.add()
的配置类型定义
src/time/typedefs/TimelineEvent.js
内部事件对象的类型定义
src/time/events/COMPLETE_EVENT.js
Timeline的
'complete'
事件常量
src/time/events/index.js
事件命名空间的入口文件