1

I am calling a function from 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')
  }

I am unable to call the openLearnMoreModal function from inside the set Timeout function, it gives an error

ERROR TypeError: _this.openLearnMoreModal is not a function

Milad
  • 27,506
  • 11
  • 76
  • 85
Abhishek
  • 61
  • 2
  • 8

2 Answers2

3

The problem is inside timeout you change the "this" reference, try this example:

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); 
 }
3

Either

Use bind(this) :

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

OR use arrow function

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

OR bind it to another variable with 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); 
 }
Milad
  • 27,506
  • 11
  • 76
  • 85
  • This should be the correct answer. The other answer is misleading in that it is not the `setTimeout` that is the cause but the `function` keyword. – Kyryll Tenin Baum Nov 26 '18 at 05:49