javascript - 检查间隔是否存在,如果存在,清除间隔并开始一个新的
问题描述
我正在编写倒计时日期脚本。但是,我正在使用的环境在提交时不会刷新页面,因此我遇到了创建多个间隔的问题。我相信如果有办法检查是否有间隔运行,然后清除它并创建一个新的。但我不确定如何做到这一点。当然,如果有比我目前设置代码的方式更好的策略,那么也可以随意提供。
我的代码:
//get ready for a-togglin'
var finishedMessage = document.getElementById('finshedMessage');
//get dates value
var dateValue = document.getElementById('dateInput').innerText;
var dateEntered = new Date(dateValue);
//set the date we're counting down too
var targetDate = new Date(dateEntered).getTime();
//Update the countdown every second
var countInterval = setInterval(function() {
var now = new Date().getTime();
//get time remaining from now
var timeRemaining = targetDate - now;
//time calculations : days, hours, minutes and seconds
var days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
//When the countdown is finished, report back completion text
if (timeRemaining <= 0 || NaN) {
finishedMessage.style.display = "inline-block";
clearInterval(countInterval);
} else {
//if day is over a year count the years remaining if no years just count days
if (days > 365) {
var years = Math.floor(days / 365);
days = days % 365;
document.getElementById("report").innerHTML = years + "Y " + days + "D " + hours + "H " + minutes + "M " + seconds + "s ";
} else {
//report the remaining time to report div
document.getElementById("report").innerHTML = days + "D " + hours + "H " + minutes + "M " + seconds + "s ";
}
}
}, 1000);
解决方案
恐怕没有如何清除所有声明的间隔而不从它们返回值。但是您可以在第一次运行时保存对全局window
对象的引用,以便您可以随时重置它:
if (window.countInterval) clearInterval(window.countInterval)
window.countInterval = setInterval(function () {
/* your code here */
})
推荐阅读
- excel - VBA - 如何使用 VLookup 从动态变化的数据透视表中检索总计
- python - 生成六角瓷砖网格,从中心点顺时针旋转
- string - 在 python 3.x 中,如何从列表中的字符串中删除子字符串?
- java - 如何找到没有 id 名称或值的复杂标签?
- ios - 使用 Core Bluetooth& 向外围设备发送数据时的延迟
- r - 为相关图设置两位数,但某些值已四舍五入为一位
- java - 如何使用 Java JDBC 实现 queryacceleration=all 和 packageset?
- mysql - 加入两个查询与联合都只返回单个值?
- rsync - rsync:错误:最多可以指定 20 个 --compare-dest 参数
- javascript - Draftjs如何从光标位置应用粗体?