gpt4 book ai didi

javascript - 无法清除设置间隔功能

转载 作者:行者123 更新时间:2023-11-30 11:00:15 26 4
gpt4 key购买 nike

我正在为计时器创 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com