Skip to content

Instantly share code, notes, and snippets.

@aranajhonny
Forked from ncou/interval.js
Created September 17, 2020 21:54
Show Gist options
  • Select an option

  • Save aranajhonny/7d0cc8ffad00bac68831f6c7973fb42b to your computer and use it in GitHub Desktop.

Select an option

Save aranajhonny/7d0cc8ffad00bac68831f6c7973fb42b to your computer and use it in GitHub Desktop.

Revisions

  1. Jasdeep Khalsa created this gist Apr 20, 2015.
    23 changes: 23 additions & 0 deletions interval.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    // http://stackoverflow.com/questions/7279567/how-do-i-pause-a-window-setinterval-in-javascript

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

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

    var resume = function() {
    start = new Date();
    timerId = window.setTimeout(function() {
    remaining = delay;
    resume();
    callback();
    }, remaining);
    };

    this.resume = resume;

    this.resume();
    }
    24 changes: 24 additions & 0 deletions timeout.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    function Timer(callback, delay) {
    var timerId, start, remaining = delay;

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

    this.resume = function() {
    start = new Date();
    window.clearTimeout(timerId);
    timerId = window.setTimeout(callback, remaining);
    };

    this.resume();
    }

    var timer = new Timer(function() {
    alert("Done!");
    }, 1000);

    timer.pause();
    // Do some stuff...
    timer.resume();