2017-03-09 121 views
0

是否有可能在jScript中使用多個匿名setTimeout函數執行類似以下操作?javascript匿名setTimeout函數

var eventCounter; 

// wait for eventCounter to be equal to 1 
console.log('eventCounter is now equal to one'); 

// pause for eventCounter to be equal to 2 
console.log('eventCounter is now equal to two'); 

// finally, wait for eventCounter to be equal to 3 
console.log('eventCounter is now equal to three'); 

我希望這樣的事情本來是可行的:

setTimeout(() => {     // fake code 
    if (eventCounter <= 1234) {  
     this();      // fake code, this() is not a function 
    } else { 
     console.log('eventCounter is now over 1234'); 
    } 
}, 200); 

也許承諾是要走的路?

否則它看起來像我最終以某種深嵌入的嵌套執行循環與多個函數名稱,我曾希望避免。

非常感謝。

+1

你可能想看看promise和'async' /'await'語法。後者是標準化的,但在大多數JavaScript引擎(node.js,瀏覽器等)中尚未實現,但是您可以通過Babel(等等)運行代碼以將'async' /'await'轉換爲瀏覽器支持的代碼。 – Frxstrem

+0

你只是想每秒鐘都會打勾嗎? –

+0

什麼是'eventCounter'?誰增加它? – Bergi

回答

0

我發現這對SO,但不幸的是我無法記得在那裏我發現它:

var waitValue = false; 
var counter = 0; 
(function tester() { 
    if (waitValue) { 
     console.log('finally true'); 
    } else { 
     if (counter > 1000) { 
      console.log('waited too long'); 
      process.exit; 
     } else { 
      console.log('still waiting, counter = ' + counter++); 
      setTimeout(tester, 1000); 
     } 
    } 
})(); 
// wait a few seconds and enter this into the console: 
var waitValue = false; 

,另一個也許更優秀的想法是suggested here

(function loop(counter) { 
     if (waitValue) { 
      console.log('waitValue is now true'); 
      resolve('FIRST PROMISE'); 
     } else if (counter <= 0) { // dont wait forever. 
      reject('waited too long'); 
     } else { 
      console.log('Count down: ' + counter); 
      setTimeout(loop.bind(null, counter-1), 3000); 
     } 
    })(counter); // initial value of count-down