jQuery Stop Loop Animation Timer

The jQuery timer that used for loop animation in previous post will be executed infinitely. Sometimes we wish to stop the timer when some set criteria are met. I am still using the bouncing basketball used in previous post as an example. Now the bouncing basketball will be stopped after bouncing for 10 times.

The stopTime() function of jQuery timer plugin can be used to stop the timer execution.

The complete jQuery codes are below:

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Stop Loop Animation Bouncing Ball</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript" src="jquery.timers.js" ></script>

<script type="text/javascript">
      $(document).ready(function(){

        // Declare a varible to monitor the timer
        var i = 10;

        // Bounce the basketball in every one second
        $("#basketball").everyTime(1000, function(){    

                 $("#basketball")
                // animate the basketball to the top in 0.6 seconds
                .animate({top:"0px"}, 600)
                // drop the basketball to the bottom in 0.4 seconds
                .animate({top:"184px"}, 400);

                // Display number on text field
                jQuery(".loopAnimationCounter").text(i);

                i = i - 1;

                // Run only 10 times
                if (i < 0) {
                $("#basketball").stopTime();
                }

          });

       });
</script>

</head>
<body>

<h1>jQuery Stop Bouncing Ball Animation</h1>

Bouncing remains:<span class="loopAnimationCounter">...</span>

<div id="frame">
      <div id="basketball"></div>
</div>

</body>
</html>

Therefore the jQuery timer stop when it meets the set criteria.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>