javascript setTimeout定时器步长函数

javascript setTimeout timer step function

本文关键字:函数 定时器 setTimeout javascript      更新时间:2023-09-26

我正在尝试使用自定义计时器创建一个函数,它将推进我正在运行的动画的一帧。我有计时器能够暂停和恢复的时刻,但我还没有能够找出一种方法来得到一个步骤函数的工作。我的动画超时延迟设置为25毫秒。

下面是我正在处理的:

Delay = 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();
}

我很感激任何人能给我的任何帮助,我还在学习,从来没有很好的定时器或定时器事件。

我设法解决了我自己的问题!这是我最终得到的结果。

//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()被调用。