jquery wait for multiple complete events

后端 未结 5 1618
无人及你
无人及你 2020-12-16 01:23

I want to use jQuery\'s load function to load some content into a div, and I want to also call jQuery\'s animate function.

$(\'#div         


        
相关标签:
5条回答
  • 2020-12-16 01:52

    You'll have to keep count of how many of your events have completed, and then use that as a test in your callback:

    var complete = 0;
    
    $('#div1').load('...', function() {
        complete++;
        callback();
    });
    $('html,body').animate({
        ...: ...}, ..., '...', function(){
        complete++;
        callback();
    });
    
    function callback(){
        if ( complete < 2 ) return;
        // both are complete
    }
    
    0 讨论(0)
  • 2020-12-16 01:54
    var _loadComplete = false;
    var _animateComplete = false;
    
    $('#div1').load('...', function() {
        // load complete
        _loadComplete = true;
        checkComplete(); 
    });
    
    $('html,body').animate({
        ...: ...}, ..., '...', function(){
        // animate complete
        _animateComplete = true;
        checkComplete();
    });
    
    function checkComplete() {
        if(_loadComplete && _animateComplete)
            runThirdFunction();
    });
    
    0 讨论(0)
  • 2020-12-16 01:56

    Sounds like a job for Deferred: http://api.jquery.com/category/deferred-object/

    var load = $.Deferred(function (dfd) {
      $('#div1').load(…, dfd.resolve);
    }).promise();
    
    var animate = $('html,body').animate(…);
    
    $.when(load, animate).then(function () {
      // Do your thing here!
    });
    
    0 讨论(0)
  • 2020-12-16 02:04

    Use:

    $('#div1').queue(function(){ /* do stuff */ });
    

    This way you can queue functions to execute one after the other.

    0 讨论(0)
  • 2020-12-16 02:06

    Set a flag in LoadComplete and call your own 'allComplete' function. Set another flag in AnimateComplete and call that same 'allComplete' function.

    In allComplete you check if both flags are set. If they are, both async functions are complete and you can call your third function.

    Instead of setting flags (separate variables), you can also add 1 to a global counter, that way, you can increase the number of async functions to wait for without having to introduce extra flag variables.

    0 讨论(0)
提交回复
热议问题