2014-11-14 59 views
-1

我需要暂停while循环基于一个条件如何暂停一个jQuery while循环有条件暂停长度

var i = 2 

while (i) { 
    if (i == 2) { 
     //pause loop for 5 seconds 
     //execute function1(); 
    } else { 
     //pause loop for 4 seconds 
     //execute function2(); 
    } 
} 

我怎么能做到这一点一定的时间。 谢谢

+1

这没有什么意义,为什么你需要while循环,什么是'做'应该做的? – adeneo 2014-11-14 15:47:28

+1

“jquery while循环”? :) – 2014-11-14 15:48:55

+1

JavaScript中没有睡眠/等待。 – epascarello 2014-11-14 15:53:29

回答

1

你可以做这样的事情:

var i = 2, 
    method1 = function() { 
     //do your thing 
     start(); 
    }, 
    method2 = function() { 
     //do your thing 
     start(); 
    }, 
    start = function() { 
     if(i && i == 2) { 
      setTimeout(method1,5000); 
     } 
     else if(i) { 
      setTimeout(method2,4000); 
     } 
    } 
; 

你需要调用start()方法的延迟方法结束。这样,你可以避免在5秒钟之前调用大量的setTimeout(method1,5000)。

+0

你打败了我:)这是我做的一个小提琴,虽然基本上是一样的东西。 http://jsfiddle.net/ubq2Lqzv/ – 2014-11-14 16:01:18