2013-08-27 25 views
1

我有一个JavaScript函数;从那个叫做延迟功能。设置超时后需要继续使用javascript函数

function(){ 
    // code 

    doDelay(); 

    // some other functionality.... 
} 

function doDelay(){ 
    setTimeout(function() {alert("after wait");}, 10000); 
} 

等待10秒后警报即将到来after wait。但它不再继续我的主要功能some other functionality.... ..延迟后我想执行剩余的功能。我怎样才能做到这一点?

+2

认沽'一些其他的功能...'的'setTimeout'里面的功能。 –

+0

http://stackoverflow.com/questions/13363622/jquery-run-function-after-settimeout – Sasidharan

+0

我不明白这里的问题。 – speti43

回答

3

setTimeout函数不会延迟执行。相反,它会安排一个函数在稍后执行。要做你想做的事情,你需要将你的代码改为:

function(){ 
... 
... 
    doDelay(function(){ 

     some other functionality.... 

    }); 
} 

function doDelay(callback){ 
    setTimeout(function() {callback()}, 10000); 
} 

确实,javascript已经有了一个doDelay函数。这就是所谓的setTimeout

function(){ 
... 
... 

    setTimeout(function(){ 

     some other functionality.... 

    },10000); 
} 

如果你想外功能也推迟后,自带代码执行,还需要一个回调传递给它:

function foo (callback){ 
... 
... 
    doDelay(function(){ 

     some other functionality.... 

     callback(); 

    }); 
} 

这样,例如,它可以让你重写这样的事情:

​​3210

这样:

foo(function(){ 
    // do other stuff after foo... 
}); 

你基本上需要围绕回调重构你的逻辑。

0

难道你不能将其他功能包装在另一个功能中,那么从你的SetTimeout调用那个函数呢?

function(){ 
    doDelay(); 
} 

function doDelay(){ 
    setTimeout(function() {alert("after wait");andTheRest();}, 10000); 
} 

function andTheRest(){ 
    //Rest of the stuff here 
} 
0
doDelayAndThenContinue(){ 
      setTimeout(function() {alert("after wait"); 
       //do other functionality here 
      }, 10000); 

    } 

取出做的主要方法等功能,并把在setTimeout的