How do I chain or queue custom functions using JQuery?

前端 未结 15 1402
暗喜
暗喜 2020-12-04 19:49

I have multiple functions the do different animations to different parts of the HTML. I would like to chain or queue these functions so they will run the animations sequenti

15条回答
  •  遥遥无期
    2020-12-04 20:40

    The jQuery Queue code is not as well documented as it could be, but the basic idea is this:

    $("#some_element").queue("namedQueue", function() {
      console.log("First");
      var self = this;
      setTimeout(function() {
        $(self).dequeue("namedQueue");
      }, 1000);
    });
    
    $("#some_element").queue("namedQueue", function() {
      console.log("Second");
      var self = this;
      setTimeout(function() {
        $(self).dequeue("namedQueue");
      }, 1000);
    });
    
    $("#some_element").queue("namedQueue", function() {
      console.log("Third");
    });
    
    $("#some_element").dequeue("namedQueue");
    

    If you run this code, you will see "First" in the console, a pause of 1s, see "Second" in the console, another pause of 1s, and finally see "Third" in the console.

    The basic idea is that you can have any number of named queues bound to an element. You remove an element from the queue by calling dequeue. You can do this yourself manually as many times as you want, but if you want the queue to run automatically, you can simply call dequeue inside the queued up function.

    Animations in jQuery all run inside a queue called fx. When you animate an element, it automatically adds the new animation on the queue and calls dequeue if no animations are currently running. You can insert your own callbacks onto the fx queue if you wish; you will just need to call dequeue manually at the end (as with any other queue use).

提交回复
热议问题