Documentation

Cookbook/wait

From jQuery JavaScript Library

Jump to: navigation, search

« Back to Cookbook

wait[time][type] )

Simple wrapper enabling setTimout within chained functions.
Special thanks to nlogax in #jquery on freenode.
Arguments:
time (Optional)Number
type (Optional)String

Examples:
Pausing in between animations.

    $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };
    function runIt() {
      $("div").wait()
              .animate({left:'+=200'},2000)
              .wait()
              .animate({left:'-=200'},1500,runIt);
    }
    runIt();

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  
  <script>
  $(document).ready(function(){
    
    $.fn.wait = function(time, type) {
        time = time || 1000;
        type = type || "fx";
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };
    function runIt() {
      $("div").wait()
              .animate({left:'+=200'},2000)
              .wait()
              .animate({left:'-=200'},1500,runIt);
    }
    runIt();

  });
  </script>
  <style>
  div { margin:3px; width:40px; height:40px;
        position:absolute; left:0px; top:30px; 
        background:green; }
  div.newcolor { background:blue; }
  span { color:red; }
  </style>
</head>
<body>
  
  <span></span>
  <div></div>
</body>
</html>

NameType