Javascript 如何在我的功能中清除计时器?

Javascript 如何在我的功能中清除计时器?,javascript,timer,Javascript,Timer,与本期相关的所有资料都在这里 打开p1.html,雪将自动飞舞。 单击停止按钮无法停止飞行sonw 可能是清除间隔(计时器)无法运行。 如何修复它 js的一部分 function stopFly(){ clearInterval(timer); document.getElementById("startButton").disabled = ""; document.getElementById("stopButton").disabled = "disabled";

与本期相关的所有资料都在这里

打开p1.html,雪将自动飞舞。
单击
停止按钮
无法停止飞行sonw

可能是
清除间隔(计时器)无法运行。
如何修复它

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();">

您从未在
onload
函数中指定
计时器
变量。因此,区间运行时没有指针

window.onload = function () {
    createManySnow();
    window.timer = setInterval(startFly, 100);
};

您从未在
onload
函数中分配
timer
变量。因此,区间运行时没有指针

window.onload = function () {
    createManySnow();
    window.timer = setInterval(startFly, 100);
};

必须将创建的计时器分配给变量

let startFlyInterval;
function stopFly(){
    clearInterval(startFlyInterval);
    document.getElementById("startButton").disabled = "";
    document.getElementById("stopButton").disabled = "disabled";
}

window.onload = function(){
    createManySnow();
    startFlyInterval = setInterval(startFly, 100);
} 

必须将创建的计时器分配给变量

let startFlyInterval;
function stopFly(){
    clearInterval(startFlyInterval);
    document.getElementById("startButton").disabled = "";
    document.getElementById("stopButton").disabled = "disabled";
}

window.onload = function(){
    createManySnow();
    startFlyInterval = setInterval(startFly, 100);
} 

您忘了将
setInterval
的返回值分配给
onload
处理程序中的
timer
。您忘了将
setInterval
的返回值分配给
onload
处理程序中的
timer
。您从未从
startFlyInterval
读取数据。这并不能解决OP的问题。您永远不会从
startFlyInterval
读取。这并不能解决OP的问题。