2015-06-24 118 views
0

我對javascript很陌生,我正在嘗試學習時間事件。我試圖實現一個函數,它需要號碼並執行function1那個號碼的次數,然後執行function2。但是在每次執行之間,我想設置一個間隔。例如,function1打印「foo」和function2打印「bar」。如果功能的輸入號碼爲「3」&間隔爲5秒,則最終打印應爲foo,foo,foo,bar,foo,foo,foo,bar ....,每隔5秒。 我試過for循環和while循環。Javascript:在所需的時間間隔內排除2個函數

var i=0; 
while (i < 4){//number of times to repeat "function" 
    if (i%4 == 0){ 
     setInterval(function(){ 
      console.log("bar"); 
     },2000);//interval between functions 
    } 
    else{ 
     setInterval(function(){ 
      console.log("foo"); 
     },2000);//interval 
    } 
    i++; 
    if (i==4) i = 0; 
} 

回答

0
function fooBar(foo,delay){ 
    var i=1; 
    setInterval(function(){ 
     if (i%(foo+1) ==0){ 
      console.log("BAR"); 
     } 
     else { 
      console.log("foo"); 
     } 
     i++; 
     //set i back to 0. not necessary, though 
     if (i==(foo+1)){ 
      i=0; 
     } 
    },delay); 
} 
fooBar(3,1000);//number of "foo"s , delay in ms 
2

有你錯過了許多東西。

  1. setInterval「設置」將在將來某個時間執行的異步任務(在您的代碼中爲2000ms)。通話結束後,立即執行下一行。另外,如果您希望任務只運行一次,則應使用setTimeoutsetInterval導致任務在無盡的「循環」中執行(至少直到調用clearInterval)。
  2. 您的while條件是多餘的。我將永遠不會等於或高於4,因爲您在while塊中重置它(在最後的if中)。這似乎是故意的,但後來就沒有理由讓所有的條件(使用while(true)

一個解決方案,你想可能是什麼:

var maxPrints = 20; // Otherwise this will never end... 
 

 
function nextInterval(i) { 
 
    console.log(i == 0 ? 'bar' : 'foo'); 
 
    if(--maxPrints > 0) 
 
    setTimeout(function() { nextInterval((i + 1) % 4); }, 2000); 
 
} 
 
nextInterval(0);

或者你可以通過一個電話setInterval這樣做:

var maxPrints = 20; // Otherwise this will never end... 
 
var i = 0, interval; 
 

 
function nextInterval() { 
 
    console.log((i++ % 4) == 0 ? 'bar' : 'foo'); 
 
    if(--maxPrints <= 0) 
 
    clearInterval(interval); 
 
} 
 
interval = setInterval(nextInterval, 2000);

+0

感謝您的指點。該解決方案,但是,不起作用。 –

+0

我知道。固定... – Amit

0

嘗試

var i = 0, 
 
    num = 3, 
 
    interval = setInterval(function() { 
 
    if (i < num) { 
 
     console.log('foo') 
 
    } else { 
 
     console.log('bar') 
 
    } 
 

 
    if (i++ == num) { 
 
     i = 0; 
 
    } 
 
    }, 500);

1

的方式,我會處理這是使功能的運行列表,以撥打:

function loopFunctions(functions, delay) 
 
{ 
 
    var i = 0; 
 

 
    return setInterval(function() { 
 
     // call current function 
 
     functions[i](); 
 
     // advance pointer and loop if necessary 
 
     i = (i + 1) % functions.length; 
 
    }, delay); 
 
} 
 

 
var foo = function() { console.log('foo'); }; 
 
var bar = function() { console.log('bar'); }; 
 

 
loopFunctions([foo, foo, foo, bar], 2000);

這是比較容易填充該數組:

var fns = Array.apply(null, new Array(3)).map(function() { 
    return foo; 
}).concat([bar]); 
0

而不是setInterval的兩個功能,setInterval的一個函數,有條件調用兩個功能。

+0

添加代碼到您的答案 –

相關問題