javascript: pause setTimeout ();


118

Se ho un timeout attivo in esecuzione che è stato impostato var t = setTimeout("dosomething()", 5000),

C'è comunque per metterlo in pausa e riprenderlo?


C'è un modo per ottenere il tempo rimanente sul timeout corrente?
o devo in una variabile, quando il timeout è impostato, memorizzare l'ora corrente, quindi ci fermiamo, otteniamo la differenza tra ora e allora?


1
Per coloro che si stanno chiedendo, la pausa è ad esempio: un div è impostato per scomparire in 5 secondi, a 3 secondi (quindi 2 secondi rimanenti) l'utente posiziona il mouse sul div, metti in pausa il timeout, una volta che l'utente sposta il mouse sul div lo riprendi, 2 secondi dopo scompare.
Hailwood

Risposte:


260

Potresti avvolgere in window.setTimeoutquesto modo, che penso sia simile a quello che stavi suggerendo nella domanda:

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

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

    this.resume = function() {
        start = Date.now();
        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();

3
@yckart: Rolled back, sorry. È una buona aggiunta tranne che l'aggiunta di parametri aggiuntivi a setTimeout()non funziona in Internet Explorer <= 9.
Tim Down

4
Se lo fai timer.resume(); timer.resume();, finirai per avere due timeout in parallelo. Ecco perché dovresti clearTimeout(timerId)prima o fare un if (timerId) return;cortocircuito all'inizio del curriculum.
kernel

2
Ehi, mi è piaciuta questa risposta, ma ho dovuto tirare: var timerId, start, remaining;fuori dall'ambito della classe e aggiungere di remaining = delay;nuovo all'interno per catturare il parametro. Funziona come un fascino però!
phillihp

1
@ Josh979: Non hai davvero bisogno di farlo ed è una cattiva idea farlo perché espone variabili che dovrebbero essere interne. Forse hai incollato il codice all'interno di un blocco (ad esempio all'interno di un if (blah) { ... }) o qualcosa del genere?
Tim Down

1
Per qualche motivo questo funziona solo una volta per me dopo essere stato inizializzato.
peterxz

17

Qualcosa di simile dovrebbe fare il trucco.

function Timer(fn, countdown) {
    var ident, complete = false;

    function _time_diff(date1, date2) {
        return date2 ? date2 - date1 : new Date().getTime() - date1;
    }

    function cancel() {
        clearTimeout(ident);
    }

    function pause() {
        clearTimeout(ident);
        total_time_run = _time_diff(start_time);
        complete = total_time_run >= countdown;
    }

    function resume() {
        ident = complete ? -1 : setTimeout(fn, countdown - total_time_run);
    }

    var start_time = new Date().getTime();
    ident = setTimeout(fn, countdown);

    return { cancel: cancel, pause: pause, resume: resume };
}

Sono passato +new Date()a new Date().getTime()dato che è più veloce: jsperf.com/date-vs-gettime
yckart

9

No. Avrai bisogno di annullarlo ( clearTimeout), misurare il tempo da quando lo hai avviato e riavviarlo con la nuova ora.


7

Una versione leggermente modificata della risposta di Tim Downs . Tuttavia, poiché Tim ha annullato la mia modifica, devo rispondere io stesso. La mia soluzione rende possibile utilizzare extra argumentscome terzo (3, 4, 5 ...) parametro e azzerare il timer:

function Timer(callback, delay) {
    var args = arguments,
        self = this,
        timer, start;

    this.clear = function () {
        clearTimeout(timer);
    };

    this.pause = function () {
        this.clear();
        delay -= new Date() - start;
    };

    this.resume = function () {
        start = new Date();
        timer = setTimeout(function () {
            callback.apply(self, Array.prototype.slice.call(args, 2, args.length));
        }, delay);
    };

    this.resume();
}

Come ha detto Tim, i parametri extra non sono disponibili in IE lt 9, tuttavia ho lavorato un po 'in modo che funzionasse oldIEanche in.

Uso: new Timer(Function, Number, arg1, arg2, arg3...)

function callback(foo, bar) {
    console.log(foo); // "foo"
    console.log(bar); // "bar"
}

var timer = new Timer(callback, 1000, "foo", "bar");

timer.pause();
document.onclick = timer.resume;

6

"Pausa" e "riprendi" non hanno molto senso nel contesto di setTimeout , che è una cosa una tantum . Intendi setInterval? Se è così, no, non puoi metterlo in pausa, puoi solo annullarlo ( clearInterval) e riprogrammarlo di nuovo. Dettagli di tutti questi nella sezione Timer delle specifiche.

// Setting
var t = setInterval(doSomething, 1000);

// Pausing (which is really stopping)
clearInterval(t);
t = 0;

// Resuming (which is really just setting again)
t = setInterval(doSomething, 1000);

16
Nel contesto di setTimeout, mettere in pausa e riprendere ha ancora senso.
dbkaplun

6

Il Timeout è stato abbastanza facile da trovare una soluzione, ma l'intervallo è stato un po 'più complicato.

Ho ideato le seguenti due classi per risolvere questo problema:

function PauseableTimeout(func, delay){
    this.func = func;

    var _now = new Date().getTime();
    this.triggerTime = _now + delay;

    this.t = window.setTimeout(this.func,delay);

    this.paused_timeLeft = 0;

    this.getTimeLeft = function(){
        var now = new Date();

        return this.triggerTime - now;
    }

    this.pause = function(){
        this.paused_timeLeft = this.getTimeLeft();

        window.clearTimeout(this.t);
        this.t = null;
    }

    this.resume = function(){
        if (this.t == null){
            this.t = window.setTimeout(this.func, this.paused_timeLeft);
        }
    }

    this.clearTimeout = function(){ window.clearTimeout(this.t);}
}

function PauseableInterval(func, delay){
    this.func = func;
    this.delay = delay;

    this.triggerSetAt = new Date().getTime();
    this.triggerTime = this.triggerSetAt + this.delay;

    this.i = window.setInterval(this.func, this.delay);

    this.t_restart = null;

    this.paused_timeLeft = 0;

    this.getTimeLeft = function(){
        var now = new Date();
        return this.delay - ((now - this.triggerSetAt) % this.delay);
    }

    this.pause = function(){
        this.paused_timeLeft = this.getTimeLeft();
        window.clearInterval(this.i);
        this.i = null;
    }

    this.restart = function(sender){
        sender.i = window.setInterval(sender.func, sender.delay);
    }

    this.resume = function(){
        if (this.i == null){
            this.i = window.setTimeout(this.restart, this.paused_timeLeft, this);
        }
    }

    this.clearInterval = function(){ window.clearInterval(this.i);}
}

Questi possono essere implementati come tali:

var pt_hey = new PauseableTimeout(function(){
    alert("hello");
}, 2000);

window.setTimeout(function(){
    pt_hey.pause();
}, 1000);

window.setTimeout("pt_hey.start()", 2000);

Questo esempio imposterà un Timeout sospendibile (pt_hey) che è programmato per avvisare, "hey" dopo due secondi. Un altro timeout mette in pausa pt_hey dopo un secondo. Un terzo Timeout riprende pt_hey dopo due secondi. pt_hey corre per un secondo, si ferma per un secondo, quindi riprende a correre. pt_hey si attiva dopo tre secondi.

Ora per gli intervalli più complicati

var pi_hey = new PauseableInterval(function(){
    console.log("hello world");
}, 2000);

window.setTimeout("pi_hey.pause()", 5000);

window.setTimeout("pi_hey.resume()", 6000);

Questo esempio imposta un intervallo di pausa (pi_hey) per scrivere "hello world" nella console ogni due secondi. Un timeout mette in pausa pi_hey dopo cinque secondi. Un altro timeout riprende pi_hey dopo sei secondi. Quindi pi_hey si attiverà due volte, correrà per un secondo, si fermerà per un secondo, correrà per un secondo e poi continuerà ad attivarsi ogni 2 secondi.

ALTRE FUNZIONI

  • clearTimeout () e clearInterval ()

    pt_hey.clearTimeout();e pi_hey.clearInterval();serve come un modo semplice per cancellare i timeout e gli intervalli.

  • getTimeLeft ()

    pt_hey.getTimeLeft();e pi_hey.getTimeLeft();restituirà quanti millisecondi devono trascorrere prima che si verifichi il trigger successivo.


Puoi spiegare i tuoi pensieri, perché abbiamo bisogno di una classe complessa per mettere in pausa una setInterval? Penso che un semplice if(!true) return;farà il trucco, o mi sbaglio?
yckart

2
Ho fatto in modo che tu possa letteralmente mettere in pausa l'intervallo, invece di saltare semplicemente una chiamata quando si attiva. Se, in un gioco, viene rilasciato un power-up ogni 60 secondi e metto in pausa il gioco appena prima che stia per innescarsi, usando il tuo metodo, dovrò aspettare un altro minuto per un altro power-up. Non è veramente una pausa, è solo ignorare una chiamata. Invece, il mio metodo si sta effettivamente mettendo in pausa e, pertanto, il potenziamento viene rilasciato "in tempo" rispetto al gioco.
TheCrzyMan

2

Avevo bisogno di calcolare il tempo trascorso e quello rimanente per mostrare una barra di avanzamento. Non è stato facile usare la risposta accettata. "setInterval" è migliore di "setTimeout" per questa attività. Quindi, ho creato questa classe Timer che puoi usare in qualsiasi progetto.

https://jsfiddle.net/ashraffayad/t0mmv853/

'use strict';


    //Constructor
    var Timer = function(cb, delay) {
      this.cb = cb;
      this.delay = delay;
      this.elapsed = 0;
      this.remaining = this.delay - self.elapsed;
    };

    console.log(Timer);

    Timer.prototype = function() {
      var _start = function(x, y) {
          var self = this;
          if (self.elapsed < self.delay) {
            clearInterval(self.interval);
            self.interval = setInterval(function() {
              self.elapsed += 50;
              self.remaining = self.delay - self.elapsed;
              console.log('elapsed: ' + self.elapsed, 
                          'remaining: ' + self.remaining, 
                          'delay: ' + self.delay);
              if (self.elapsed >= self.delay) {
                clearInterval(self.interval);
                self.cb();
              }
            }, 50);
          }
        },
        _pause = function() {
          var self = this;
          clearInterval(self.interval);
        },
        _restart = function() {
          var self = this;
          self.elapsed = 0;
          console.log(self);
          clearInterval(self.interval);
          self.start();
        };

      //public member definitions
      return {
        start: _start,
        pause: _pause,
        restart: _restart
      };
    }();


    // - - - - - - - - how to use this class

    var restartBtn = document.getElementById('restart');
    var pauseBtn = document.getElementById('pause');
    var startBtn = document.getElementById('start');

    var timer = new Timer(function() {
      console.log('Done!');
    }, 2000);

    restartBtn.addEventListener('click', function(e) {
      timer.restart();
    });
    pauseBtn.addEventListener('click', function(e) {
      timer.pause();
    });
    startBtn.addEventListener('click', function(e) {
      timer.start();
    });

2

/ rilanciare

Versione ES6 che utilizza zucchero sintattico di classe y 💋

(leggermente modificato: aggiunto start ())

class Timer {
  constructor(callback, delay) {
    this.callback = callback
    this.remainingTime = delay
    this.startTime
    this.timerId
  }

  pause() {
    clearTimeout(this.timerId)
    this.remainingTime -= new Date() - this.startTime
  }

  resume() {
    this.startTime = new Date()
    clearTimeout(this.timerId)
    this.timerId = setTimeout(this.callback, this.remainingTime)
  }

  start() {
    this.timerId = setTimeout(this.callback, this.remainingTime)
  }
}

// supporting code
const pauseButton = document.getElementById('timer-pause')
const resumeButton = document.getElementById('timer-resume')
const startButton = document.getElementById('timer-start')

const timer = new Timer(() => {
  console.log('called');
  document.getElementById('change-me').classList.add('wow')
}, 3000)

pauseButton.addEventListener('click', timer.pause.bind(timer))
resumeButton.addEventListener('click', timer.resume.bind(timer))
startButton.addEventListener('click', timer.start.bind(timer))
<!doctype html>
<html>
<head>
  <title>Traditional HTML Document. ZZz...</title>
  <style type="text/css">
    .wow { color: blue; font-family: Tahoma, sans-serif; font-size: 1em; }
  </style>
</head>
<body>
  <h1>DOM &amp; JavaScript</h1>

  <div id="change-me">I'm going to repaint my life, wait and see.</div>

  <button id="timer-start">Start!</button>
  <button id="timer-pause">Pause!</button>
  <button id="timer-resume">Resume!</button>
</body>
</html>


1

Potresti esaminare clearTimeout ()

o mettere in pausa a seconda di una variabile globale impostata quando viene raggiunta una determinata condizione. Come se si premesse un pulsante.

  <button onclick="myBool = true" > pauseTimeout </button>

  <script>
  var myBool = false;

  var t = setTimeout(function() {if (!mybool) {dosomething()}}, 5000);
  </script>

1

Puoi anche implementarlo con eventi.

Invece di calcolare la differenza di orario, inizi e interrompi l'ascolto di un evento "tick" che continua a funzionare in background:

var Slideshow = {

  _create: function(){                  
    this.timer = window.setInterval(function(){
      $(window).trigger('timer:tick'); }, 8000);
  },

  play: function(){            
    $(window).bind('timer:tick', function(){
      // stuff
    });       
  },

  pause: function(){        
    $(window).unbind('timer:tick');
  }

};

1

Se stai comunque usando jquery, controlla il plugin $ .doTimeout . Questa cosa è un enorme miglioramento rispetto a setTimeout, inclusa la possibilità di tenere traccia dei tuoi timeout con un singolo ID di stringa che specifichi e che non cambia ogni volta che lo imposti, e implementare facili cancellazioni, cicli di polling e debouncing e Di Più. Uno dei miei plugin jquery più utilizzati.

Sfortunatamente, non supporta la pausa / ripresa fuori dagli schemi. Per questo, dovresti racchiudere o estendere $ .doTimeout, presumibilmente in modo simile alla risposta accettata.


Speravo che doTimeout avrebbe messo in pausa / riprendi, ma non lo vedo quando guardo la documentazione completa, gli esempi di loop e persino la fonte. Il punto più vicino alla pausa che ho potuto vedere è annullare, ma poi dovrei ricreare di nuovo il timer con la funzione. Ho dimenticato qualcosa?
ericslaw

Mi dispiace averti condotto sulla strada sbagliata. Ho rimosso quell'inesattezza dalla mia risposta.
Ben Roberts

1

Dovevo essere in grado di mettere in pausa setTimeout () per la funzione simile a una presentazione.

Ecco la mia implementazione di un timer in pausa. Integra i commenti visti sulla risposta di Tim Down, come una pausa migliore (commento del kernel) e una forma di prototipazione (commento di Umur Gedik).

function Timer( callback, delay ) {

    /** Get access to this object by value **/
    var self = this;



    /********************* PROPERTIES *********************/
    this.delay = delay;
    this.callback = callback;
    this.starttime;// = ;
    this.timerID = null;


    /********************* METHODS *********************/

    /**
     * Pause
     */
    this.pause = function() {
        /** If the timer has already been paused, return **/
        if ( self.timerID == null ) {
            console.log( 'Timer has been paused already.' );
            return;
        }

        /** Pause the timer **/
        window.clearTimeout( self.timerID );
        self.timerID = null;    // this is how we keep track of the timer having beem cleared

        /** Calculate the new delay for when we'll resume **/
        self.delay = self.starttime + self.delay - new Date().getTime();
        console.log( 'Paused the timer. Time left:', self.delay );
    }


    /**
     * Resume
     */
    this.resume = function() {
        self.starttime = new Date().getTime();
        self.timerID = window.setTimeout( self.callback, self.delay );
        console.log( 'Resuming the timer. Time left:', self.delay );
    }


    /********************* CONSTRUCTOR METHOD *********************/

    /**
     * Private constructor
     * Not a language construct.
     * Mind var to keep the function private and () to execute it right away.
     */
    var __construct = function() {
        self.starttime = new Date().getTime();
        self.timerID = window.setTimeout( self.callback, self.delay )
    }();    /* END __construct */

}   /* END Timer */

Esempio:

var timer = new Timer( function(){ console.log( 'hey! this is a timer!' ); }, 10000 );
timer.pause();

Per testare il codice, usa timer.resume()e timer.pause()alcune volte e controlla quanto tempo è rimasto. (Assicurati che la tua console sia aperta.)

Usare questo oggetto al posto di setTimeout () è facile come sostituirlo timerID = setTimeout( mycallback, 1000)con timer = new Timer( mycallback, 1000 ). Quindi timer.pause()e timer.resume()sono a tua disposizione.



0

Implementazione del dattiloscritto basata sulla risposta più votata

/** Represents the `setTimeout` with an ability to perform pause/resume actions */
export class Timer {
    private _start: Date;
    private _remaining: number;
    private _durationTimeoutId?: NodeJS.Timeout;
    private _callback: (...args: any[]) => void;
    private _done = false;
    get done () {
        return this._done;
    }

    constructor(callback: (...args: any[]) => void, ms = 0) {
        this._callback = () => {
            callback();
            this._done = true;
        };
        this._remaining = ms;
        this.resume();
    }

    /** pauses the timer */
    pause(): Timer {
        if (this._durationTimeoutId && !this._done) {
            this._clearTimeoutRef();
            this._remaining -= new Date().getTime() - this._start.getTime();
        }
        return this;
    }

    /** resumes the timer */
    resume(): Timer {
        if (!this._durationTimeoutId && !this._done) {
            this._start = new Date;
            this._durationTimeoutId = setTimeout(this._callback, this._remaining);
        }
        return this;
    }

    /** 
     * clears the timeout and marks it as done. 
     * 
     * After called, the timeout will not resume
     */
    clearTimeout() {
        this._clearTimeoutRef();
        this._done = true;
    }

    private _clearTimeoutRef() {
        if (this._durationTimeoutId) {
            clearTimeout(this._durationTimeoutId);
            this._durationTimeoutId = undefined;
        }
    }

}

0

Puoi fare come di seguito per rendere setTimeout sospesa sul lato server (Node.js)

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

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

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

    this.resume();
};

e puoi controllarlo come di seguito

var timer = new PauseableTimeout(function() {
    console.log("Done!");
}, 3000);
setTimeout(()=>{
    timer.pause();
    console.log("setTimeout paused");
},1000);

setTimeout(()=>{
    console.log("setTimeout time complete");
},3000)

setTimeout(()=>{
    timer.resume();
    console.log("setTimeout resume again");
},5000)

-1

Non credo che troverai niente di meglio di clearTimeout . Ad ogni modo, puoi sempre programmare un altro timeout in un secondo momento, invece di "riprenderlo".


-1

Se hai diversi div da nascondere, potresti usare un setIntervale un numero di cicli per fare come in:

<div id="div1">1</div><div id="div2">2</div>
<div id="div3">3</div><div id="div4">4</div>
<script>
    function hideDiv(elm){
        var interval,
            unit = 1000,
            cycle = 5,
            hide = function(){
                interval = setInterval(function(){
                    if(--cycle === 0){
                        elm.style.display = 'none';
                        clearInterval(interval);
                    }
                    elm.setAttribute('data-cycle', cycle);
                    elm.innerHTML += '*';
                }, unit);
            };
        elm.onmouseover = function(){
            clearInterval(interval);
        };
        elm.onmouseout = function(){
            hide();
        };
        hide();
    }
    function hideDivs(ids){
        var id;
        while(id = ids.pop()){
            hideDiv(document.getElementById(id));
        }
    }
    hideDivs(['div1','div2','div3','div4']);
</script>
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.