简体   繁体   English

javascript setTimeout 定时器步进函数

[英]javascript setTimeout timer step function

I am trying to create a function using a custom timer which will advance one frame of my animation I am running.我正在尝试使用自定义计时器创建一个函数,该函数将推进我正在运行的动画的一帧。 I have the timer able to pause and resume at the moment, but I have not been able to figure out a way to get a step function working.我现在可以让计时器暂停和恢复,但是我无法找到一种方法来使步进功能正常工作。 My animation timeout delay is set at 25 ms.我的动画超时延迟设置为 25 毫秒。

Here is what I'm working with:这是我正在使用的内容:

Delay = 25延迟 = 25

    //This function is a custom timer that tracks the start time of a timeout and calculates the remaining time
    // in order to resume at the appropriate frame of animation.
function Timer(callback, delay) {
    var timerId, start, remaining = delay;

    this.pause = function() {
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
        animate = false;
    };

    this.resume = function() {
        start = new Date();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
        animate = true;
    };

    this.resume();
}

I appreciate any help that anyone can give me, I'm still learning and have never been good with timers or timer events.我感谢任何人可以给我的任何帮助,我仍在学习并且从来没有擅长计时器或计时器事件。

UPDATE I managed to remedy my own problem!更新我设法解决了我自己的问题! Here's what I ended up with overall.这就是我最终得出的结论。

//This function is a custom timer that tracks the start time of a timeout and calculates the remaining time
// in order to resume at the appropriate frame of animation.
function Timer(callback, delay){
    var timerId, start, remaining = delay;

    this.pause = function(){
        window.clearTimeout(timerId);
        remaining -= new Date() - start;
        animate = false;
    };

    this.resume = function(){
        start = new Date();
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
        animate = true;
    };

    this.step = function(){
        timer.pause();
        animate = false;
        advanceAnimation(true);
    };

    this.resume();
}

您可以使用 Interval 代替 Timeout,它会像一个步骤一样重复,直到调用 clearInterval() 为止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM