簡體   English   中英

JavaScript-在while循環中執行setTimeout

[英]javascript - do while loop setTimeout

我已經閱讀了許多有關setTimeout主題,但是在理解如何將這個函數實現到循環中仍然存在問題。 我會盡力告訴你我的意思。

function RandomHit(anyArray)
{    
    var turechange = false;
    do{
        setTimeout(function(){
            var random = Math.floor(Math.random()*2);
            if(random===0)
            {
                turechange = true;
                console.log(random);
            }
            if(random===1)
            {
                console.log(random);    
            }
        }, 2000);
    }while(!turechange);
}

每次循環再次出現時,我都會嘗試將代碼減慢2000毫秒。 但這是行不通的。

您對JavaScript的單線程性質有疑問(至少在這種情況下-盡管有一些例外)。

代碼中實際發生的是內部無休止的while循環,其中大量的setTimeout()函數排隊。 但是由於您的代碼實際上從未離開過while循環,因此這些回調將不會執行。

一種解決方案是在setTimeout()回調中觸發下一個超時函數,如下所示:

function RandomHit(anyArray) {   

    var turechange = false;

    function timerFct(){
      var random = Math.floor(Math.random()*2);
      if(random===0)
      {
          turechange = true;
          console.log(random);
      }
      if(random===1)
      {
          console.log(random);    
      }

      if( !turechange ) {
        setTimeout( timerfct, 2000 );
      }
    }

    timerFct();
}

另一種解決方案是使用setIntervall()clearIntervall()

function RandomHit(anyArray)
{    
    function timerFct(){
      var random = Math.floor(Math.random()*2);
      if(random===0)
      {
          turechange = true;
          console.log(random);
      }
      if(random===1)
      {
          console.log(random);    
      }

      if( turechange ) {
        clearTimeout( timeoutHandler );
      }
    }
    var turechange = false,
        timeoutHandler = setInterval( timerFct, 2000 );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM