Javascript-当计时器达到0时如何重置按钮计数器



我正在尝试获得一个简单的点击计数器函数来倒计时用户可以使用的点击次数,其中剩余的点击次数将每 24 小时重置一次。 我已经浏览了一些教程,并在用户最大化点击后在警报中直观地实现了它。但是,我如何仅在计时器达到 0 时才重置计数。

.HTML

<p><button onclick="clickCounter()" type="button">Click</button></p>
<div id="result"></div>

JavaScript

function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
if(typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if(Number(localStorage.clickcount) <= 0){
alert('You have max the number of connect nTime left: '+ hours+':'+min+':'+sec);
localStorage.clickcount =4;
}
localStorage.clickcount = Number(localStorage.clickcount)-1
} 
else
{
localStorage.clickcount = 4;
} 
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}

下面是它如何运行的示例。目前,我已将其设置为在警报弹出后立即重置,我只是在弄清楚如何在计时器启动时自动重置。感谢您的任何反馈和帮助

示例链接

您可以设置间隔函数来检查时间并在时间结束时重置值。我已经更改了您的代码以添加间隔函数

checkClickCount();
function clickCounter() {
var d = new Date();
var hours = 24 - d.getHours();
var min = 60 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
if (Number(localStorage.clickcount) < 1) {
alert('You have max the number of connect nTime left: ' + hours + ':' + min + ':' + sec);
return;
}
localStorage.clickcount = Number(localStorage.clickcount) - 1
} else {
localStorage.clickcount = 4;
}
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks left.";
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support web storage...";
}
}
var intv = null;
function checkClickCount(){
// interval run a function in a specified period of time
intv = window.setInterval(function(){
var currentTime = new Date();
var remainDateTime = new Date();
remainDateTime.setHours(24 - currentTime.getHours());
remainDateTime.setMinutes(60 - currentTime.getMinutes());
remainDateTime.setSeconds(60 - currentTime.getSeconds());

if(localStorage.clickcount > 1){
return;
}
// If the remaining times finished, the click count will be reset
if(remainDateTime.getHours() + remainDateTime.getMinutes() + remainDateTime.getSeconds() == 0){
localStorage.clickcount = 4;
document.getElementById("result").innerHTML = "You have " + localStorage.clickcount + " clicks";
return;
}
document.getElementById("result").innerHTML = "You will get 4 more clicks in " + remainDateTime.getHours() + ":" + remainDateTime.getMinutes() + ":" + remainDateTime.getSeconds() + " later.";
}, 1000);
}

最新更新