Javascript: how to exit loop by clicking a button

I've done some searches and I'm not even sure if what I want to do is good javascript practice. I have a while loop that I would like to exit early if the stop button is pressed.

$( "#go" ).click(function() {
  var gotime = 1;
  while (gotime < 100) {
    for(i = 0; i < 2; i++){
      var divName = "floatName" + i;
      console.log(divName);
      $( "#" + divName ).animate({
        left: Math.random()*500 + "px",
        top: Math.random()*500 + "px"
      }, 500, function() {
        // Animation complete.
      });
    };

    gotime += 1;

    $( "stop" ).click(function() {
      gotime = 101;
    });
    };
});

      

This does not work. Initially, I had an infinite loop (not increasing the time).

http://jsfiddle.net/cvoxe465/

+3


source to share


3 answers


It actually stops if you wait a while. The problem is that you run the animation very often and you $.animate

have to queue it up. There is a method $. Stop , which allows you to stop the current animation. DEMO

$( "#stop" ).click(function() {
  gotime = 101;
  $('#floatName0, #floatName1').stop(true, true);
});

      



EDIT:

Please note that there is a bug in the code you provided. Instead, $("stop")

you need to use $("#stop")

.

+3


source


animate

does not block the loop. The animations add up and then execute, but the cycle ends much earlier. Here's what works:

var loopAllowed = false;
$('#go').click(function(){
    loopAllowed = true;
    var max = 2;
    var loop = function(){
        for(var i = 0; i < max; i++){
            var divName = "floatName" + i;
            $( "#" + divName ).animate({
                left: Math.random()*500 + "px",
                top: Math.random()*500 + "px"
            }, 500, i === max - 1 && loopAllowed ? loop : undefined);
        }
    };
    loop();
});

$('#stop').click(function(){
    loopAllowed = false;    
});

      



JSFiddle . We manually call the loop

function after the animation ends (passing it as a callback function). If loopAllowed

false (for example, set to false by clicking #stop

) it will not be passed as a callback and the loop will stop.

+1


source


You can use setInterval

:

Js:

var interval;
$("#go").click(function () {
    var gotime = 1;
    interval = setInterval(function () {
        for (i = 0; i < 2; i++) {
            var divName = "floatName" + i;
            console.log(divName);
            $("#" + divName).css({
                left: Math.random() * 500 + "px",
                top: Math.random() * 500 + "px"
            });
        };
        gotime += 1;
        if (gotime > 100) {
            clearInterval(interval);
        }
    }, 500)
});
$("#stop").on('click', function () {
    clearInterval(interval);
});

      

CSS

#randomFloat {
    color: red;
}
#floatName1, #floatName0 {
    transition : 0.5s left, 0.5s top;
}

      

Fiddle

0


source







All Articles