Подтвердить что ты не робот

Javascript: pause setTimeout();

Если у меня есть активный тайм-аут, который был установлен через var t = setTimeout("dosomething()", 5000),

Можно ли приостановить и возобновить его?


Есть ли способ получить оставшееся время в текущем тайм-ауте?
или я должен иметь переменную, когда установлен тайм-аут, сохранить текущее время, тогда мы делаем паузу, получаем разницу между временем и потом?
4b9b3361

Ответ 1

Вы можете обернуть window.setTimeout следующим образом: я думаю, это похоже на то, что вы предлагали в вопросе:

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();

Ответ 2

Что-то вроде этого должно сделать трюк.

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 };
}

Ответ 3

Нет. Вам нужно отменить его (clearTimeout), измерить время с момента его запуска и перезапустить его с новым временем.

Ответ 4

Немного измененная версия Tim Downs answer. Однако, поскольку Tim откат меня редактировал, я должен сам ответить на это. Мое решение позволяет использовать дополнительный arguments как третий (3, 4, 5...) параметр и очистить таймер:

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();
}

Как отметил Тим, дополнительные параметры недоступны в IE lt 9, однако я немного поработал, чтобы он работал и в oldIE.

Использование: 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;

Ответ 5

"Пауза" и "резюме" на самом деле не имеют особого смысла в контексте setTimeout, который является разовым. Вы имеете в виду setInterval? Если это так, нет, вы не можете приостановить его, вы можете только отменить его (clearInterval), а затем переписать его еще раз. Подробности обо всех из них в разделе Таймеры спецификации.

// 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);

Ответ 6

Тайм-аут был достаточно легким, чтобы найти решение, но Интервал был немного сложнее.

Я разработал следующие два класса для решения этих проблем:

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);}
}

Они могут быть реализованы как таковые:

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

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

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

В этом примере будет установлен прерывистый тайм-аут (pt_hey), который планируется предупредить "эй" через две секунды. Другой тайм-аут приостанавливает pt_hey через одну секунду. Третий тайм-аут возобновляет pt_hey через две секунды. pt_hey работает в течение одной секунды, пауза в течение одной секунды, а затем возобновляется. Спустя три секунды триггер pt_hey.

Теперь для более сложных интервалов

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

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

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

Этот пример устанавливает прерывистый интервал (pi_hey) для записи "hello world" в консоли каждые две секунды. Тайм-аут приостанавливает pi_hey через пять секунд. Другой тайм-аут возобновляет pi_hey через шесть секунд. Таким образом, pi_hey запускается дважды, запускается в течение одной секунды, приостанавливается на одну секунду, запускается в течение одной секунды, а затем продолжает запускать каждые 2 секунды.

ДРУГИЕ ФУНКЦИИ

  • clearTimeout() и clearInterval()

    pt_hey.clearTimeout(); и pi_hey.clearInterval(); служат как простой способ очистки тайм-аутов и интервалов.

  • getTimeLeft()

    pt_hey.getTimeLeft(); и pi_hey.getTimeLeft(); вернут, сколько миллисекунд до запланированного следующего триггера.

Ответ 7

Мне нужно было рассчитать прошедшее и оставшееся время, чтобы показать индикатор прогресса. Принимая ответ, было непросто. 'setInterval' лучше, чем 'setTimeout' для этой задачи. Итак, я создал этот класс Timer, который вы можете использовать в любом проекте.

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();
    });

Ответ 8

Я не думаю, что вы найдете что-нибудь лучше, чем clearTimeout. В любом случае, вы всегда можете запланировать еще один тайм-аут позже, вместо этого "возобновить" его.

Ответ 9

Вы также можете реализовать его с помощью событий.

Вместо вычисления разницы во времени вы начинаете и прекращаете прослушивание события "tick", которое продолжает работать в фоновом режиме:

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');
  }

};

Ответ 10

Если вы все равно используете jquery, ознакомьтесь с плагином $. doTimeout. Эта вещь является огромным улучшением по сравнению с setTimeout, в том числе позволяет вам отслеживать ваши тайм-ауты с единственным указанным идентификатором строки, который не изменяется при каждом его настройке, а также обеспечивает легкую отмену, опрос петлей и debouncing и Больше. Один из моих самых популярных плагинов jquery.

К сожалению, он не поддерживает pause/resume из коробки. Для этого вам нужно будет обернуть или расширить $.doTimeout, предположительно аналогично принятому ответу.

Ответ 11

Мне нужно было приостановить функцию setTimeout() для слайд-шоу.

Вот моя собственная реализация паутинного таймера. Он объединяет комментарии, увиденные в ответ Tim Down, такие как лучшая пауза (комментарий ядра) и форма прототипирования (комментарий 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 */

Пример:

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

Чтобы проверить код, используйте timer.resume() и timer.pause() несколько раз и проверьте, сколько осталось времени. (Убедитесь, что консоль открыта.)

Использование этого объекта вместо setTimeout() так же просто, как замена timerID = setTimeout( mycallback, 1000) на timer = new Timer( mycallback, 1000 ). Тогда timer.pause() и timer.resume() доступны вам.

Ответ 12

Вы можете посмотреть clearTimeout()

или пауза в зависимости от глобальной переменной, которая задается при ударе определенного условия. Как кнопка нажата.

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

  <script>
  var myBool = false;

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

Ответ 13

/возрождать

Версия ES6 с использованием синтаксического сахара Class-y 💋

(слегка измененный: добавлен 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>

Ответ 14

Если у вас есть несколько div, чтобы скрыть, вы можете использовать setInterval и несколько циклов, например:

<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>