Reputation: 194
I want to shutdown my computer 1 min after I push button, and if I push button again it will shutdown after it push last time.
for(var i=1; i<=10; ++i){
setDelay();
}
var nn;
function setDelay(){
clearTimeout(nn);
nn = setTimeout(function(){
console.log("shutdown");
}, 60000);
}
But my code have another "setTimeout" too. Will it work fine ?, or will it damage my other setTimeout ?
Upvotes: 4
Views: 1611
Reputation: 708026
I'd suggest you create an object that allows you to add time to it:
function Timer(t, fn) {
this.fn = fn;
this.time = Date.now() + t;
this.updateTimer();
}
Timer.prototype.addTime = function(t) {
this.time += t;
this.updateTimer();
}
Timer.prototype.stop = function() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
Timer.prototype.updateTimer = function() {
var self = this;
this.stop();
var delta = this.time - Date.now();
if (delta > 0) {
this.timer = setTimeout(function() {
self.timer = null;
self.fn();
}, delta);
}
}
Then, you can use it like this:
var timer = new Timer(60000, function() {
console.log("shutdown");
});
// add one second of time
timer.addTime(1000);
// add one minute of time
timer.addTime(1000 * 60);
Upvotes: 4