2

I want to call one function when timer value becomes 0. When I click on card, one popup opens and then timer starts. Below is the code:

openModal() {
  switch (area) {
    case 'a':
      var self_t = this;
      uid = 11;
      let timer = 20;
      let interval = setInterval(function () {
          let elementID = document.getElementById('float-div');
          if(elementID == null) {
            timer = this.inSeconds;
          }
          if(timer >= 0) {
            if(elementID) {
              elementID.innerHTML = String(timer);
            }
          }
          if (--timer == 0) {
              if(elementID) {
                  elementID.innerHTML = '0';
              }
              if(area == "a") {
                 self_t.callFunction(uid); // here it is not going, I put debugger here but i can see it doesn't go here!                          
                 clearInterval(interval);
              }
          }
    }, 1000);
    break;

    case 'b':
    console.log('something else');
    break;
  }
}

callFunction(uid) {
  console.log(uid);
}

already tried: using var self=this

If I use this.callFunction(uid) then it throws an error.

Pathik Vejani
  • 4,263
  • 8
  • 57
  • 98

2 Answers2

2

Use arrow function for this. Below is a snippet try this out it will do the trick. Read more about Arrow functions

openModal() {
  switch (area) {
    case 'a':
      uid = 11;
      let timer = 20;
      let interval = setInterval(() => {
        let elementID = document.getElementById('float-div');
        if (elementID == null) {
          timer = this.inSeconds;
        }
        if (timer >= 0) {
          if (elementID) {
            elementID.innerHTML = String(timer);
          }
        }
        if (--timer == 0) {
          if (elementID) {
            elementID.innerHTML = '0';
          }
          if (area == "abc") {
            this.callFunction(uid); // here it is not going, I put debugger here but i can see it doesn't go here!                          
            clearInterval(interval);
          }
        }
      }, 1000);
      break;

    case 'b':
      console.log('something else');
      break;
  }
}

callFunction(uid) {
  console.log(uid);
}

UPDATE:

No need of the below statement when using arrow functions. this will be available inside the function.

  var self_t = this;

Hope this helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
1

Maybe you should modify these codes

 if(elementID == null) {
            timer = this.inSeconds;
          }

to

 if(elementID == null) {
            timer = self_t.inSeconds;
          }
Chivenh
  • 114
  • 4