JQuery countdown timer, automatically refreshes after it hits 0

I haven't been able to find any good examples, but I'm looking for some simple jQuery examples for a countdown 30 seconds

that will essentially refresh the current page after it hits 0

.

Each account should be displayed in an item <div>

.

+3


source to share


1 answer


Here's a very simple implementation to get the right idea,

http://jsfiddle.net/2jajy50p/

$(window).ready( function() {

    var time = 30

    setInterval( function() {

        time--;

        $('#time').html(time);

        if (time === 0) {

            location.reload();
        }    


    }, 1000 );

});

      

As requested, here's an explanation of what happens: on window load, setInterval

sets the duration for each anonymous function call. Every 1000 milliseconds (1 second) the variable time is decremented by 1. Each call, a new time is added to the DOM using the jQuery method .html()

. Inside the same function, there is one conditional statement that determines if the time is === 0; as soon as this evaluates to true, the page is reloaded using the method location.reload()

.

EDIT

In a comment, asking if there is a way to make the timer run once, even after page reloads:



I suggested using localStorage (which I admit is not ideal), but anywhere, here is a working implementation.

EVEN NEW EDIT

I went back to this and looked over my answer. And since I'm a nerd, I wanted to create a more dynamic, accessible solution:

var timerInit = function(cb, time, howOften) {
  // time passed in is seconds, we convert to ms
  var convertedTime = time * 1000;
  var convetedDuration = howOften * 1000;
  var args = arguments;
  var funcs = [];

  for (var i = convertedTime; i > 0; i -= convetedDuration) {
    (function(z) {
      // create our return functions, within a private scope to preserve the loop value
      // with ES6 we can use let i = convertedTime
      funcs.push(setTimeout.bind(this, cb.bind(this, args), z));

    })(i);
  }

  // return a function that gets called on load, or whatever our event is
  return function() {

    //execute all our functions with their corresponsing timeouts
    funcs.forEach(function(f) {
      f();
    });
  };

};

// our doer function has no knowledge that its being looped or that it has a timeout
var doer = function() {
  var el = document.querySelector('#time');
  var previousValue = Number(el.innerHTML);
  document.querySelector('#time').innerHTML = previousValue - 1;
};


// call the initial timer function, with the cb, how many iterations we want (30 seconds), and what the duration between iterations is (1 second)
window.onload = timerInit(doer, 30, 1);

      

http://jsbin.com/padanuvaho/edit?js,output

+11


source







All Articles