2017-05-20 8 views
2

JavaScriptがsetTimeout(またはそれに相当するもの)を作成して、時間がなくなるまで次の行に移動しないようにする方法があるのだろうかと思います。例えば、以下のコードを意図した通りに動作させる方法はありますか?setTimeoutを同期させる方法はありますか?

var cntr = 0; 

while(cntr < 25) { 
    setTimeout(200); //wait 200ms to continue to next line 
    console.log(cntr); //or some other task 
    cntr++; 
} 

ありがとうございました!

+1

いや、いない可能に動作するはずです。何のためにそれが必要ですか? – Ryan

答えて

3

setTimeoutは、決して同期できません。しかし、あなたは、あなたが望むものを達成するために再帰を使用することができます - あなたが得ることができる

var cntr = 0 

function printCounter() { 
    console.log(cntr) 
    cntr++ 
    if(cntr < 25) { 
    setTimeout(printCounter, 200) 
    } 
} 

setTimeout(printCounter, 200) 
-1

'SetInterval()'関数を試しましたか?

setInterval(loop(), 200); 

    function loop() { 
     console.log(cntr); 
     cntr++; 
    } 

200msごとに何かが発生します。

0

最も近いasync/awaitを使用しています。ここで問題となるのは、多くのブラウザではサポートされていないため、これをサポートしたいブラウザによっては良い解決策ではない可能性があります。

私はこれが(私はそれをテストしたところである)最新のChromeブラウザで動作します知っている、とノード7

// Tell the browser that this function is asynchronous 
async function myFunc() { 
    // Await for the promise to resolve 
    await new Promise((resolve) => { 
     setTimeout(() => { 
      // Resolve the promise 
      resolve(console.log('hello')); 
     }, 3000); 
    }); 
    // Once the promise gets resolved continue on 
    console.log('hi'); 
} 

// Call the function 
myFunc(); 
関連する問題