簡體   English   中英

setTimeout 內的函數調用未執行

[英]function call within setTimeout not executing

我正在輸入框的 keyup 上執行函數delayFilter() 我想在用戶停止輸入並運行filterProducts()函數后延遲 1 秒。 但是,在 setTimeout 內執行filterProducts()時,我收到控制台錯誤“this.filterProducts 不是函數”。 當在 setTimeout 之外時,這個函數被很好地調用。 為什么會拋出這個錯誤?

  delayFilter() {
    let timeout = null;
    clearTimeout(timeout);

    timeout = setTimeout(function() {
      this.filterProducts();
    }, 1000);
  }

  filterProducts() {
    //do stuff
  }

那是因為回調中的 this 並沒有引用外部的對象。

嘗試這個:

delayFilter() {
    let timeout = null;
    clearTimeout(timeout);
    let self = this;
    timeout = setTimeout(function() {
      self.filterProducts();
    }, 1000);
  }

  filterProducts() {
    //do stuff
  }

您也可以嘗試箭頭功能。 原因可以在這里看到: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

箭頭函數表達式是正則函數表達式的一種語法緊湊的替代方案,盡管它自身沒有綁定到 this、arguments、super 或 new.target 關鍵字。

delayFilter() {
    let timeout = null;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      this.filterProducts();
    }, 1000);
  }

  filterProducts() {
    //do stuff
  }

您需要在setTimeout回調中綁定函數的作用域。 如果您的平台支持,最簡單的方法是使用箭頭函數。

timeout = setTimeout(() => this.filterProducts(), 1000);

您還可以將范圍保存在變量中。

var self = this;
timeout = setTimeout(funciton() { self.filterProducts() }, 1000);

或者,您可以手動綁定它。 如果您想傳遞函數,這很有用。

timeout = setTimeout(function() {...}.bind(this), 1000);

暫無
暫無

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

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