JavaScript网页倒计时器停止按钮无法正常生效问题求助
倒计时停止按钮异常修复方案
问题根因
- 存储定时器ID的
timedown是countDown函数内部的局部变量,作用域仅局限在countDown函数内,stopCount函数没有权限访问该变量,无法获取到正在运行的定时器ID,自然没法中止倒计时。 stopCount中的逻辑完全错误:countDown.length返回的是函数定义的形参数量,你将函数对象当作数组遍历的操作无法获取到任何定时器ID,自然不会生效。
修复方案
我们只需要把定时器ID存到两个函数都能访问到的全局作用域即可,同时额外增加重复点击启动按钮的防重复处理,避免同时开启多个定时器:
// 全局作用域存储定时器ID let timedown = null; function countDown(){ // 先清空已有定时器,避免重复点击启动开多个倒计时 if(timedown) { clearInterval(timedown); } var currTime = 55 timedown = setInterval(function() { currTime = currTime - 1; document.getElementById("countdowntimer").innerHTML ="The time is:" + currTime; if(currTime == 0){ clearInterval(timedown); // 倒计时结束后重置定时器ID timedown = null; document.getElementById("countdowntimer").innerHTML = "BLASTOFF!" } else if(currTime < 25){ document.getElementById("countdowntimer").innerHTML = "Half way to launch " + currTime; } }, 1000); } function stopCount() { // 直接清除全局存储的定时器即可 if(timedown) { clearInterval(timedown); timedown = null; } }
你原有的HTML代码不需要做任何修改,替换JS代码后停止按钮即可正常生效。
内容的提问来源于stack exchange,提问作者Raider 9640
相关产品推荐
相关产品推荐

