Search code examples
javascripttimer

How to clear the timer in my function?


All the material related with this issue are here.

All the material related with this issue

Open the p1.html, snow will fly automatically.
Click stop button can't stop the flying sonw.

Maybe the clearInterval(timer); in stopFly function can't run.
How to fix it?

Part of js.

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

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

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

Solution

  • You never assign the timer variable in your onload function. So an interval is running without a pointer.

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