0

I have a set of objects to be displayed at different times using setTimeout() function in JavaScript. What I did was to have a loop running, for every element I initialized a setTimeout event for itself.

The code I used to setTimeout for each element:

for (i = currentIndex; i < this.items.length; i++) {
    var object = "element#"+i;
    var delay = 10*i;
    this.keepDelay[id] = new Timer(function() {
                                $("#objectSet").css("display", "none").html(object).fadeIn("fast");
                                currentIndex = id;
                            }, delay);
}

The Timer class is

function Timer(callback, delay) {
    var timerId, start, remaining = delay;

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

    // works    
    this.resume = function() {
        start = new Date();
        id = currentIndex;
        timerId = window.setTimeout(callback, remaining);
    };

    // does NOT work
    this.speedup = function() {
        remaining -= 100;
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    }

    // does NOT work
    this.slowdown = function() {
        remaining += 100;
        window.clearTimeout(timerId);
        timerId = window.setTimeout(callback, remaining);
    }

    this.resume();
}

The resume() and pause() methods do work. resume() attempts to display each object one after another depending on the delay value. pause() is self-explanatory. These two are working fine.

Now I want to speed up and slow down the delay of the objects, I try to write speedup() and slowdown() methods but somehow they wouldn't work.

Looking at the code I can't find why it wouldn't, maybe I've focused on it for too long so I need to seek help from a fresh mind.

user3583721
  • 327
  • 2
  • 4
  • 14

1 Answers1

1

You need to calculate the time that has already elapsed so you can figure out how much to set a new timer for. Here's an example for .speedup():

this.speedup = function() {
    window.clearTimeout(timerId);
    var elapsed = new Date() - start;
    remaining-= elapsed + 100;
    if (remaining > 0) {
        this.resume();
    } else {
        callback();
    }
}

You would do something similar for .slowdown().


It occurs to me this could be done a little simpler:

this.speedup = function() {
    this.pause();
    remaining-= 100;
    this.resume();
}

this.slowdown = function() {
    this.pause();
    remaining+= 100;
    this.resume();
}

and, then you change this.resume() to this to make sure remaining doesn't go negative:

this.resume = function() {
    start = new Date();
    id = currentIndex;
    if (remaining > 0) {
        timerId = window.setTimeout(callback, remaining);
    } else {
        callback();
    }
};
jfriend00
  • 683,504
  • 96
  • 985
  • 979