function Timer(func, delay) { var done = false; var callback = function() { done = true; return func(); }; var startTime = Date.now(); var timeout = setTimeout(callback, delay); this.add = function(ms) { if (!done) { this.cancel(); delay = delay - (Date.now() - startTime) + ms; timeout = setTimeout(callback, delay); } }; this.cancel = function() { clearTimeout(timeout); }; this.immediately = function() { if (!done) { this.cancel(); callback(); } }; };
quick test in the console
start = Date.now(); t = new Timer(function() { console.log(Date.now() - start); }, 1000); t.add(200); start = Date.now(); t = new Timer(function() { console.log(Date.now() - start); }, 1000000); t.immediately(); t.immediately();
You can also add negative values.
start = Date.now(); t = new Timer(function() { console.log(Date.now() - start); }, 1000); t.add(-200);
David chan
source share