如何修复无法清除定时器导致雪花动画无法停止的问题?
雪花飘落停止功能修复问题
打开p1.html后,雪花会自动飘落,但点击stop button无法停止雪花飘落。推测stopFly函数中的clearInterval(timer);未执行,请问该如何修复?
现有部分JS代码:
function stopFly(){ clearInterval(timer); document.getElementById("startButton").disabled = ""; document.getElementById("stopButton").disabled = "disabled"; } window.onload=function(){ createManySnow(); setInterval(startFly,100); }
现有部分HTML代码:
<input type="button" value="new" onclick="createManySnow();"> <input type="button" id="startButton" value="start" onclick="timer=setInterval(startFly,100)"> <input type="button" id="stopButton" value="stop" onclick="stopFly();">
嘿,这个问题其实挺典型的——咱们先拆解下问题根源:
页面加载时,window.onload里直接调用了setInterval(startFly,100),但这个定时器没有赋值给全局的timer变量;而只有点击start按钮时,才会把定时器实例赋值给timer。这就导致stopFly里的clearInterval(timer)只能清除点击start按钮触发的定时器,完全碰不到页面加载时自动启动的那个定时器,所以雪花自然停不下来~
修复方法很简单,只要把页面加载时的定时器也绑定到全局timer上,同时优化下按钮的状态逻辑就行:
修改后的JS代码:
function stopFly(){ clearInterval(timer); document.getElementById("startButton").disabled = ""; document.getElementById("stopButton").disabled = "disabled"; } window.onload=function(){ createManySnow(); // 将页面加载时的定时器赋值给全局变量timer timer = setInterval(startFly,100); // 自动启动后禁用start按钮,避免重复创建定时器 document.getElementById("startButton").disabled = "disabled"; // 启用stop按钮,方便用户操作 document.getElementById("stopButton").disabled = ""; }
可选优化:增强start按钮的逻辑
如果担心用户多次点击start按钮创建多个定时器,还可以修改start按钮的点击事件,先清除已有定时器再创建新的:
<input type="button" value="new" onclick="createManySnow();"> <input type="button" id="startButton" value="start" onclick="clearInterval(timer); timer=setInterval(startFly,100); this.disabled='disabled'; document.getElementById('stopButton').disabled='';"> <input type="button" id="stopButton" value="stop" onclick="stopFly();">
这样一来,不管是页面自动启动的定时器,还是点击start重新启动的定时器,都会被统一存在timer变量里,stopFly调用clearInterval(timer)就能精准清除它,雪花也就乖乖停下来啦~
内容的提问来源于stack exchange,提问作者user7988893
相关产品推荐
相关产品推荐

