简体   繁体   中英

javascript autoreload in infinite loop with time left till next reload

i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:

<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>

i also need it to repeat itself infinitely.

thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.

(function() {
    var el = document.getElementById('time-to-update');
    var count = 30;
    setInterval(function() {
        count -= 1;
        el.innerHTML = count;
        if (count == 0) {
            location.reload();
        }
    }, 1000);
})();

A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true); .

var timer = 30;
var el = document.getElementById('time-to-update');

(function loop(el) {
  if (timer > 0) {
    el.innerHTML = timer;
    timer -= 1;
    setTimeout(function () { loop(el); }, 1000);
  } else {
    document.location.reload(true);
  }
}(el));

http://jsfiddle.net/zGGEH/1/

var timer = {
    interval: null,
    seconds: 30,

    start: function () {
        var self = this,
            el = document.getElementById('time-to-update');

        el.innerText = this.seconds; // Output initial value

        this.interval = setInterval(function () {
            self.seconds--;

            if (self.seconds == 0) 
                window.location.reload();

            el.innerText = self.seconds;
        }, 1000);
    },

    stop: function () {
        window.clearInterval(this.interval)
    }
}

timer.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM