所以我有一个基本的倒计时器,从点击事件('START CLOCK')开始的5分钟开始倒计时。我想在倒计时开始后直到倒计时结束时禁用此功能。有什么建议吗?
<html>
<head>
</head>
<body>
<h1>Countdown Clock</h1>
<div onclick="startClock()">START CLOCK</div>
<div id="clockdiv">
<div>
<span class="hours"></span>
<div class="smalltext">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="smalltext">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="smalltext">Seconds</div>
</div>
</div>
<script>
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
//var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
//'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function startClock() {
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
//var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
//daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var timeInMinutes = 5;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);
initializeClock('clockdiv', deadline);
}
</script>
</body>
</html>
答案 0 :(得分:1)
由于您通过html属性附加事件监听器,实现目标的最简单方法是简单的全局标志 - 在函数启动时将其抬起,在函数完成时将其删除。
如果函数已经在运行并且用户试图再次运行它(标志被引发),则立即返回。
答案 1 :(得分:0)
我基本上在你的函数中添加了一个标志变量。
var flag=0;
function startClock() {
function initializeClock(id, endtime) {
if(flag==0)
{
var clock = document.getElementById(id);
//var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
flag=1;
}
function updateClock() {
var t = getTimeRemaining(endtime);
//daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
flag=0;
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var timeInMinutes = 1;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);
initializeClock('clockdiv', deadline);
}
每当时钟滴答时,标志就会设置。当计数器达到0时,它会重置为原始值。
这是DEMO,时间设置为1分钟。