SeverinDK / moment-timer

Timer plugin for Moment.js that allows creation of setInterval and setTimeout-like timers.
MIT License
110 stars 33 forks source link

Timer not runs on start after delay #1

Closed fedotov closed 8 years ago

fedotov commented 8 years ago

I use the following code to schedule execution of 'update' function

moment.duration(config.updateIntervalInSeconds, 'seconds').timer({wait: intervalToUpdate, loop: true }, update);

And I expect that first run of 'update' will be in 'intervalToUpdate' seconds. But in reality the first run will be in 'config.updateIntervalInSeconds + intervalToUpdate' seconds. I've looked to source and found the reason.

Here it is.

       if (this.loop) {
            this.timer = setInterval(function() {
                self.updateStartEndTickFromDuration(self.timerDuration);
                return self.callback();
            }, this.timerDuration);
        }

When setInterval is executed it is not run the callback.

I suggest following solution

       if (this.loop) {
            self.callback();
            this.timer = setInterval(function() {
                self.updateStartEndTickFromDuration(self.timerDuration);
                return self.callback();
            }, this.timerDuration);
        }

To call self.callback() manually. What do you think?

SeverinDK commented 8 years ago

It is actually working as intended. The wait will just cause the timer to be delayed, but after that it will start counting down the interval/timeout. But I could add an attribute, to have it fire as soon as a wait duration is finished. Do you think you could use that? Something like:

{wait: 1000, executeAfterWait: true }

SeverinDK commented 8 years ago

Ï have added the attribute I mentioned above. So if you wish the timer to execute after the wait is over, you can do so like this:

moment.duration(1000).timer({
   loop: true, 
   wait: 60000, 
   executeAfterWait: true
}, function () {});

This will cause the timer to execute after one minute and then every second after that.

fedotov commented 8 years ago

Thank you.