如何按顺序调用3个函数以便一个接一个地执行它们?

168
如果我需要依次调用这些函数,
$('#art1').animate({'width':'1000px'},1000);        
$('#art2').animate({'width':'1000px'},1000);        
$('#art3').animate({'width':'1000px'},1000);        

我知道在jQuery中可以这样做:

$('#art1').animate({'width':'1000px'},1000,'linear',function(){
    $('#art2').animate({'width':'1000px'},1000,'linear',function(){
        $('#art3').animate({'width':'1000px'},1000);        
    });        
});        

但是,假设我不使用jQuery,我想调用:

some_3secs_function(some_value);        
some_5secs_function(some_value);        
some_8secs_function(some_value);        
我应该如何调用这些函数来执行some_3secs_function,并在此调用结束后,再执行some_5secs_function,在此调用结束后,再调用some_8secs_function更新: 这仍然不起作用:
(function(callback){
    $('#art1').animate({'width':'1000px'},1000);
    callback();
})((function(callback2){
    $('#art2').animate({'width':'1000px'},1000);
    callback2();
})(function(){
    $('#art3').animate({'width':'1000px'},1000);
}));

三个动画同时开始

我的错误在哪里?


你的意思是这些函数需要在恰好3、5和8秒时被调用,还是只需要一个接一个地调用? - Trass Vasston
我认为你只是对同步和异步函数执行不确定。我已经在下面更新了我的答案。希望能帮到你。 - Wayne
试试这个... https://github.com/dineshkani24/queuecall - Dineshkani
11个回答

0
如果方法1必须在方法2、3、4之后执行,可以使用JavaScript中的Deferred对象来解决。以下代码片段可能是解决方案。

function method1(){
  var dfd = new $.Deferred();
     setTimeout(function(){
     console.log("Inside Method - 1"); 
     method2(dfd);  
    }, 5000);
  return dfd.promise();
}

function method2(dfd){
  setTimeout(function(){
   console.log("Inside Method - 2"); 
   method3(dfd); 
  }, 3000);
}

function method3(dfd){
  setTimeout(function(){
   console.log("Inside Method - 3");  
   dfd.resolve();
  }, 3000);
}

function method4(){   
   console.log("Inside Method - 4");  
}

var call = method1();

$.when(call).then(function(cb){
  method4();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接