Home > other >  Js stopping repeated functions running
Js stopping repeated functions running

Time:12-08

Ok, I'm a JS noob and I've scoured these forums and Google and haven't found a working answer yet. But, I'm sure one of you moderators will instantly find the same question asked and shut this one down, so here goes.

Here's my code:

    $('#mybtn').click(function () {
        var canvas = document.getElementById('myCanvas');
        var ctx = canvas.getContext('2d', {willReadFrequently: true});
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var interations = 0;

        function drawOnCanvas() {
            iterations  ;
            //draw stuff on the canvas
            if (iterations < Number.MAX_SAFE_INTEGER - 1) {
                window.requestAnimationFrame(drawOnCanvas);
            }
        }
        drawOnCanvas();
    });

Yes, I'm drawing LOTS of pixels. It's lots of math.

Here's my problem:

If the user clicks on mybtn a second time it does clear the canvas and starts drawing again. But, the previous drawOnCanvas function doesn't stop drawing so now I have 2 drawOnCanvas functions running, both drawing at the same time. Click again, 3 drawOnCanvas running.

What I was expecting was when the button was clicked that the first running script would terminate. What I think I'm seeing is that another instance of the script is created and both are running.

I've tried setting global jQuery booleans but, when the second instance fires up and sets the boolean, the first instance doesn't seem to see it, which makes sense.

Any ideas as to how I can just have one of these running at one time? My logic is failing me.

Thanks!

CodePudding user response:

When the button is clicked, you could add a .one click listener (that fires once, next time the button is clicked) that clears the currently ongoing animation.

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
$('#mybtn').click(function () {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    let iterations = 0;
    let id;
    function drawOnCanvas() {
        iterations  ;
        //draw stuff on the canvas
        if (iterations < Number.MAX_SAFE_INTEGER - 1) {
            id = window.requestAnimationFrame(drawOnCanvas);
        }
    }
    drawOnCanvas();
    $('#mybtn').one('click', () => {
        window.cancelAnimationFrame(id);
    })
});
  • Related