简体   繁体   中英

Stop function loop without interval

I have a JS function called particleAppear which is a loop:

var particles = new Array("pt0","pt1","pt2","pt3");

function particleAppear(){
    var genPoint = Math.floor(Math.random() * (720 - 4 + 1)) + 4;
    var particle = particles[Math.floor(Math.random()*particles.length)];

    $('#particles').append('<div class="'+particle+'" style="position: absolute; top: '+genPoint+'px; left: -4px"></div>');

    var rtime1 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
    var rtime2 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
    var rtime3 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;
    var rtime4 = Math.floor(Math.random() * (42000 - 32000 + 1)) + 32000;

    $('.pt0').animate({left: '+=1280px'}, rtime1, "linear",function(){
        $(this).remove();
    });
    $('.pt1').animate({left: '+=1280px'}, rtime2, "linear",function(){
        $(this).remove();
    });
    $('.pt2').animate({left: '+=1280px'}, rtime3, "linear",function(){
        $(this).remove();
    });
    $('.pt3').animate({left: '+=1280px'}, rtime4, "linear",function(){
        $(this).remove();
    });

    var randomTimeGen = Math.floor(Math.random() * (1500 - 450 + 1)) + 450;
    setTimeout(particleAppear,randomTimeGen);
}

As you can see, the loop used is not a setInterval but a setTimeout whichs rerun the function after a random time between 450 and 1500ms. How can I stop this using JAVASCRIPT/JQUERY?

You can store the numeric id of the timeout in a variable and clear it:

var timeout = setTimeout(particleAppear,randomTimeGen);

clearTimeout(timeout);

Use clearTimeout() .

Create a variable outside of your function:

var timeout;

And in your function

timeout = setTimeout(particleAppear,randomTimeGen);

Elsewhere in your code you can call:

clearTimeout(timeout);

You can stop the function from running in the same way you might stop a function running with setInterval

var timeout;
function particleAppear(){
    /* ... */
    timeout = setTimeout(particleAppear, randomTimeGen)
}

// Somewhere else
clearInterval(timeout);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM