Angular settimeout不起作用的JavaScript

时间:2018-11-01 21:51:41

标签: javascript angular typescript settimeout

我正在从ngOnInit调用一个函数

  public ngOnInit() {
    this.idleLogout();
  }
  public idleLogout() {
    let t;
    window.onload = resetTimer;
    window.addEventListener('scroll', resetTimer, true);

    function resetTimer() {
      clearTimeout(t);
      t = setTimeout(() => {
        // this.openLearnMoreModal();
      }, 4000);
    }
  }
  public openLearnMoreModal() {
    console.log('here')
  }

我无法从set Timeout函数内部调用openLearnMoreModal函数,它给出了错误消息

错误TypeError:_this.openLearnMoreModal不是函数

2 个答案:

答案 0 :(得分:3)

问题是您更改“ this”引用的内部超时,请尝试以下示例:

public ngOnInit() {
  this.idleLogout();
}
 public idleLogout() {
  let t;
  const parentThis = this;

  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

 function resetTimer() {

  clearTimeout(t);
    t = setTimeout(() => {
    parentThis.openLearnMoreModal();
  }, 4000); 
 }

答案 1 :(得分:2)

要么

使用 bind(this)

window.onload = resetTimer.bind(this);
window.addEventListener('scroll', resetTimer.bind(this), true); 

使用arrow function

public idleLogout() {
  let t;
  const resetTimer = ()=> {
      clearTimeout(t);
      t = setTimeout(() => {
      // this.openLearnMoreModal();
      }, 4000); 
    }
  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

OR 将其绑定到另一个this变量:

public idleLogout() {
  let t;
  const resetTimer = _resetTimer.bind(this);
  window.onload = resetTimer;
  window.addEventListener('scroll', resetTimer, true); 

 function _resetTimer() {

  clearTimeout(t);
    t = setTimeout(() => {
    this.openLearnMoreModal();
  }, 4000); 
 }