Allen Pascual Allen Pascual - 6 days ago 5
HTML Question

Any idea how to stop this loop?



function draw(x, y)
{
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.fillStyle = "rgba(0,110,150,1)";
ctx.fillRect (x, 370, 20, 20);
ctx.restore();
x += 41;
var loop = setTimeout('draw('+x+','+y+')',70);
}

draw(10, 20);

.d{
width: 93%;
height: auto;
z-index: 1;
position: absolute;
}

<canvas id="canvas" class="d" width="1838" height="1050"></canvas>




Answer

loop needs to be scoped outside of the function. Then calling clearTimeout on it will stop the loop.

var loop;
function draw(x,y) {
    ...
    loop = setTimeout (...); // no "var"
    ...
}
...
draw (0,0);
setTimeout (function () {
    clearTimeout (loop);
}, 5000); // will stop the loop after 5 seconds 
Comments