【发布时间】:2019-01-10 21:28:17
【问题描述】:
我在 window.onload = function(){...} 之外声明了一个包含 setInterval 的函数和一个包含 clearInterval 的函数。但是计时器无法按预期停止
当我单击开始按钮时,我可以看到计时器正确启动,并且控制台中正在重复打印“hello”。但是,当我点击“停止”按钮时,计时器不会被清除。
我认为在加载文档时,“start_btn”和“stop_btn”的onclick函数应该准备好了,然后我使用开始按钮,它将变量“timer”设置为一个数字,然后我点击停止按钮,为什么看不到当前非空的“定时器”变量?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
<style>
*{
margin: 0px;
padding: 0px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var timer = null;
var start_btn = document.getElementById("start");
var stop_btn = document.getElementById("stop");
startFunc(start_btn, timer);
stopFunc(stop_btn, timer);
};
function startFunc(target, timer){
target.onclick = function(){
timer = setInterval(function(){
console.log("hello");
}, 300);
};
}
function stopFunc(target, timer){
target.onclick = function(){
clearInterval(timer);
};
}
</script>
</head>
<body>
<button type="button" id="start">start</button>
<button type="button" id="stop">stop</button>
</body>
</html>
【问题讨论】:
-
您的
startFunc只是在修改timer的本地副本。考虑扩大它的范围或传递一个对象,以便在作为参数传递时可以改变它。 -
感谢您,这对您有很大帮助!
标签: javascript