-1

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.

Here is what I'm working with:

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

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();
}
2
  • How it's not working? What goes wrong? Any errors in the console?
    – Teemu
    Aug 1, 2015 at 6:31
  • I have figured it out finally with only manipulating some of my animation logic. I was able to achieve my outcome by calling the timer pause function first, setting my animation boolean variable to false, and manually calling my drawing animation function one time instead of it being called by the timeout. Aug 2, 2015 at 7:19

1 Answer 1

0

Instead of a Timeout, you can use an Interval, which will repeat like a step until clearInterval() has been called.

1
  • Thanks for your help, I did not know of Intervals! Aug 2, 2015 at 7:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.