亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在JavaScript循環中添加延遲?

如何在JavaScript循環中添加延遲?

如何在JavaScript循環中添加延遲?我想在while循環中添加延遲/睡眠:我試過這樣的:alert('hi');for(var start = 1; start < 10; start++) {   setTimeout(function () {     alert('hello');   }, 3000);}只有第一種情況是真的:顯示后alert('hi'),它將等待3秒然后alert('hello')將顯示,但隨后alert('hello')將反復不斷。我想要的是,在alert('hello')3秒后顯示alert('hi')之后,它需要等待第二次3秒alert('hello'),依此類推。
查看完整描述

4 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

嘗試這樣的事情:

var i = 0, howManyTimes = 10;function f() {
    alert( "hi" );
    i++;
    if( i < howManyTimes ){
        setTimeout( f, 3000 );
    }}f();


查看完整回答
反對 回復 2019-05-28
?
慕哥6287543

TA貢獻1831條經驗 獲得超10個贊

如果使用ES6,您可以使用let以實現此目的:

for (let i=1; i<10; i++) {
    setTimeout( function timer(){
        alert("hello world");
    }, i*3000 );}

為每次迭代let聲明i了什么,而不是循環。這樣,傳遞的內容正是我們想要的。setTimeout


查看完整回答
反對 回復 2019-05-28
?
翻閱古今

TA貢獻1780條經驗 獲得超5個贊

由于ES7是等待循環的更好方法:

function timer(ms) {
 return new Promise(res => setTimeout(res, ms));}async function load () {
  for (var i = 0; i < 3; i++) {
    console.log(i);
    await timer(3000);
  }}load();

關于MDN的參考

請注意,今天很少支持ES7,因此您需要與Babel進行交互,以便在任何地方使用它。

Transpiled


查看完整回答
反對 回復 2019-05-28
  • 4 回答
  • 0 關注
  • 1846 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號