jQuery倒数计时器,点击0后自动刷新

时间:2014-08-21 00:19:16

标签: jquery countdown jquery-countdown

我还没有找到任何好的例子,但是我希望找到一些简单的jQuery示例来进行30 seconds的倒计时,一旦点击0就会刷新当前页面{1}}。

每个计数都应显示在<div>元素中。

1 个答案:

答案 0 :(得分:12)

这是一个非常简单的实现,可以帮助您找到正确的想法,

http://jsfiddle.net/2jajy50p/

$(window).ready( function() {

    var time = 30

    setInterval( function() {

        time--;

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

        if (time === 0) {

            location.reload();
        }    


    }, 1000 );

});

根据请求,这是对正在进行的操作的解释:在窗口加载时,setInterval设置每个匿名函数调用的持续时间。每1000毫秒(1秒)变量时间减1.每次调用时,新时间使用jQuery .html()方法附加到DOM。在同一个函数中,有一个条件语句确定时间是否为=== 0;一旦此计算结果为true,则使用location.reload()方法重新加载页面。

修改

根据评论,询问是否有办法让计时器运行一次,即使在页面重新加载后:

我建议使用localStorage(我承认它并不完美),但在任何地方,here都是一个有效的实现。

即使是新编辑

我回到这里,看着我的回答。而且因为我是个书呆子,我想创造一个更有活力,更可摄取的解决方案:

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