我没能找到任何好的例子,但我正在寻找一些简单的jQuery示例,用于30 seconds
的倒计时,一旦它到达0
,它将基本上刷新当前页面。
每个计数应显示在<div>
元素中
这里有一个非常简单的实现,可以让您获得正确的想法,
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。在同一个函数中,有一个条件语句确定time === 0;一旦该值为true,则使用location.reload()
方法重新加载页面。
编辑
每个评论,询问是否有办法使计时器运行一次,即使在页面重新加载后:
我建议使用localStorage(我承认它并不完美),但在任何地方,这里都是一个工作实现。
更新编辑
我回过头来仔细看我的答案。因为我是个书呆子,所以我想创造一种更有活力、更容易消化的解决方案:
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,输出