簡體   English   中英

Javascript:在匿名函數表達式上使用setTimeout

[英]Javascript : setTimeout use on an anonymous function expression

我最近開始學習JavaScript,以幫助維護某些內容,並在今天遇到了此問題:

this.moveChar = function(){  
    // body here
    setTimeout(moveChar,1000);
}

this.initialise= function(){
    this.moveChar();
}

調用初始化時,我希望可以調用moveChar,然后每1000ms重復調用一次

但是,實際上發生的是moveChar被調用一次,僅此而已。 根據我閱讀的其他stackoverflow帖子,我懷疑這可能與函數的表達而不是聲明有關。 我嘗試使用

this.moveChar = function recMove(){  
    // body here
    setTimeout(recMove,1000);
}

也沒有運氣。

關於如何解決此問題的任何建議?

編輯:我要做的主要事情是每秒調用一次moveChar函數。 如果有比setTimeout遞歸更好的方法,我可以接受

this.moveCharmoveChar ,除非this是諸如window類的全局范圍對象。

this.moveChar是對象的屬性,而moveChar將引用可見范圍鏈中的任何變量。

您可以將其更改為幾件事,以保持所使用對象的范圍:

使用箭頭功能

this.moveChar = function(){  
    // body here
    setTimeout(()=>this.moveChar(),1000);
}

使用.bind()

this.moveChar = function(){  
    // body here
    setTimeout(this.moveChar.bind(this),1000);
}

你在side bodythis嗎?
如果是這樣,則應在調用時綁定正確的上下文。

this.moveChar = function(){  
    // body here
    setTimeout(this.moveChar.bind(this), 1000);
}

或使用匿名函數:

this.moveChar = function(){  
    // body here
    var that = this;
    setTimeout(function(){
      that.moveChar();
    }, 1000);
}

或箭頭功能:

this.moveChar = function(){  
    // body here
    setTimeout(() => this.moveChar(), 1000);
}

同樣的注釋適用於setInterval變體:

this.initialise= function(){
   setInterval(this.moveChar.bind(this), 1000);
   // var that = this;
   // setInterval(function(){that.moveChar();}, 1000);

   // setInterval(() => this.moveChar(), 1000);
}

您可能要考慮使用setInterval() ,它是更適合此任務的API。

setInterval()作用是-在達到一定間隔后將重復調用給定函數。

請參閱: https//developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

引用:

重復調用函數或執行代碼段,每次調用之間有固定的時間延遲。 返回一個intervalID。

例:

假設moveChar()包含您的操作邏輯。 然后重復一遍,您將執行此1行。

let moveChar = function(){  
    // Do stuff
    console.log("Hi thanks for calling me!");
}

setInterval(moveChar, 1000);
   this.moveChar = function(){  
       // body here
     alert('called moveChar');
  }

this.initialise= function(){
     setInterval(function(){moveChar();},1000);
}

 this.initialise();//call here

暫無
暫無

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

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