我正在为计时器创 build 置间隔函数。我成功实现了set interval功能。
我需要使用清除间隔函数来停止计时器。我编写了 stop_timer 函数来停止,但我无法停止计时器。
我通过在全局变量中声明空变量来尝试它。我无法得到。以下是我试过的代码。
HTML代码:
<div id="t_demo"></div>
<button onclick="clear_timer()">clear</button>
Javascript 代码:
var x = "";
function start_timer() {
// Update the count down every 1 second
var x = setInterval(function() {
var countDownDate = new Date("2019-09-25 05:05:05");
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = now - countDownDate;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("t_demo").innerHTML = hours + ":" + minutes + ":" + seconds;
}, 1000);
}
start_timer();
function clear_timer() {
clearInterval(x);
}
最佳答案
您正在将区间分配给一个新变量。
尝试换行
var x = setInterval(function() {
到
x = setInterval(function() {
关于javascript - 无法清除设置间隔功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58100892/