javascript - 无法清除设置间隔功能
问题描述
我正在为计时器创建设置间隔功能。我成功实现了设置间隔功能。
我需要使用清除间隔功能停止计时器。我编写了 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);
}
解决方案
You are assigning the interval to a new variable.
Try changing the line
var x = setInterval(function() {
To
x = setInterval(function() {
推荐阅读
- python - 执行使用 Pyinstaller 构建的 Python 应用程序会出现“无法执行脚本主程序”
- reactjs - 从同一域服务 React 应用程序和后端服务器
- c++ - 致命错误:eigen3/Eigen/Core:没有这样的文件或目录
- c++ - 在 C++ 中仅复制二进制文件的一部分
- robotframework - 为什么在机器人框架中使用“数据驱动”库时要使用“测试模板”?
- excel - 范围变量未定义
- python - 在多个 matplotlib 轴中同步图例的位置
- c - 我的管道客户端如何等待服务器
- javascript - 为什么数据没有显示在 react-bootstrap-table 中?
- r - 定义数据框的 R for 循环中的列名更改