user687554
user687554

Reputation: 11151

Add milliseconds to timeout

I've create a timeout in JavaScript that looks like this:

var milliseconds = 3000;
var timer = setTimeout(function() { console.log('done!'); }, milliseconds);

This timer runs for 3 seconds. However, sometimes, I want to add an additional minute. My challenge is, sometimes, the timer has already started. For example, the timer may have one minute and 45 seconds left before the function is called. However, I want to add a minute such that the timeout function is called in two minutes and 45 seconds.

Is there a way to add milliseconds to a timeout in JavaScript. I don't see a function that allows this.

Upvotes: 3

Views: 1106

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138457

class Timer {
 constructor(func){
   this.func = func;
   this.timers = [];
 }
 start(time){
   setTimeout(_=>this.check(),time);
 }
 add(time){
   this.timers.push(time);
 }
 check(){
   if(!this.timers.length) return this.func();
   this.start(this.timers.shift());
 }
}

Usable like this:

var t = new Timer(_=>alert("hi"));
t.start(1000);
t.add(3000);

Basically this implements a timers queue. Adding an amount of time does not change the timer, but adds the time onto the queue. If a timer finished, it only executes the function if there are no timers left, if theres one it proceeds with it.

Upvotes: 3

Related Questions