简体   繁体   中英

stop javascript loop, setTimeout

This animation should stop playing (stop snowing) after 10 seconds. I added a function to the bottom, but it actually starts the animation after 10 seconds, rather than stopping the animation after 10 seconds.

I only want it to play for 10 seconds total time, and start right-away, see my codePen to see what I mean.

setTimeout(function() {
createSnow(20);
loop();
}, 10000)

here is a codePen to see what I mean: https://codepen.io/celli/pen/XzzjRW

What you'll want to do is create a "timer", finding the difference between when you started and the current time.

I'm not sure if you wanted createSnow(20) inside of the loop or not, so I put it before, as initialization.

createSnow(20);

const start = new Date();
while(new Date() - start < 10000) {
  loop();
}

You were close. You just needed a way to tell the system to stop the animation loop. See my codepen: https://codepen.io/intervalia/pen/zPPoBZ

I added a variable to indicate if animation should be happening:

var animating = true;

A routine to stop the animation:

function stopAnimation() {
  animating = false;
  //Add something in here to clear the screen
}

A validation check in the animation loop:

function loop() {
  if (animating) {
    draw();
    update();
    animFrame(loop);
  }
}

And changed your timeout to turn off the animation:

createSnow(150);
loop();

setTimeout(stopAnimation, 10000);

Cool animation!!

Use cancelAnimationFrame .

Sample usage

Declare cancelAnimFrame :

var cancelAnimFrame =
  window.cancelAnimationFrame ||
  window.mozcancelAnimationFrame ||
  window.webkitcancelAnimationFrame ||
  window.mscancelAnimationFrame;

Update loop function:

var animId;
function loop() {
  draw();
  update();
  animId = animFrame(loop);
}

and use animId to stop animation. (As already mentioned, starting snowing should be out of setTimeout .)

createSnow(20);
loop();
setTimeout(function() {
  cancelAnimFrame(animId)
}, 1000)

the only thing that you have to change is a little change of your code plz see this code below :

var timeOut = setTimeout(function() {
createSnow(20);
loop();
}, 10000);

clearTimeout(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