how to dynamically exit a jquery $.each()?

peter picture peter · Jun 4, 2010 · Viewed 33.4k times · Source

i have a list of images which i am getting through ajax and then using jquery $.each() i loop through the images and display a image one after the other after an interval of one second. I want the user to be able click on a stop button and so that the user can stop at a particular image if he wants to. So i need to dynamically exit $.each() when the user clicks on the stop button. Is it possible to do it?

Answer

Adeel picture Adeel · Jun 4, 2010

You can use return false to break out of each() loops early.

Example:

<script>
    $("button").click(function () {
      $("div").each(function (index, domEle) {
        // domEle == this
        $(domEle).css("backgroundColor", "yellow"); 
        if ($(this).is("#stop")) {
          $("span").text("Stopped at div index #" + index);
          return false;
        }
      });
    });

</script>

Source: http://api.jquery.com/each/