Martin AJ
Martin AJ

Reputation: 6697

How can I break a loop when I'm out of it?

Here is my code:

$(document).on('click', '.fa-search', function () {

    while(1) {
        magnifire.fadeTo('slow', 0.2).fadeTo('slow', .8);
    }
    sendAjaxRequest();

    // Here I need to break (stop) that while loop
})

As I've commented in my code, I need to stop while(1) after sendAjaxRequest(); executed. How can I do that?

Upvotes: 0

Views: 56

Answers (1)

Nisarg Shah
Nisarg Shah

Reputation: 14541

You could use setInterval and clearInterval for this. As their names suggest, setInterval sets a function to execute repeatedly at given interval (1000 ms in example below), and clearInterval stops all further executions.

var interval = setInterval(function() {
  console.log("Do something");
  //  magnifire.fadeTo('slow', 0.2).fadeTo('slow', .8);
},1000);


function Clear() {
  clearInterval(interval);
  console.log("Stop iterating");
}
<button onclick="Clear()">Click me</button>

Upvotes: 1

Related Questions