rektandpepper
rektandpepper

Reputation: 81

Simple Javascript Countdown how to update global from setintervals local function

I am pulling countdown data(just a number like 10,15..) from db and making it equal to global. just under class.

countdown:any;

 console.log(this.countdown);//i got data 10 sec
let downloadTimer=setInterval(function counter(countdown){
    countdown--;        // how to update this.countdown ?
console.log(countdown);
    if(countdown <= 0){
        clearInterval(downloadTimer);
        console.log("time is up!");
      }
    },1000,this.countdown);

I am starting with sending this.countdown to counter parameter but then how do i update this.countdown from local counter function? because when setinterval iterates it always calls this.countdown so counter stucks at first this.countdown value.

If i do it without parameter i cant access this.counter from counter local function.

Upvotes: 1

Views: 291

Answers (1)

Mark
Mark

Reputation: 92440

You are trying to pass a single scalar value, this.countdown, which is does, but you can't update that the same way you can an object or array and get the side effect of updating the original.

You could pass a reference to this and then use it to update the original:

class test {
  constructor() {
    this.countdown = 20
  }
  doit() {
    console.log(this.countdown); //i got data 10 sec
    let downloadTimer = setInterval(function counter(obj) {
      obj.countdown--; // how to update this.countdown ?
      console.log(obj.countdown);
      if (obj.countdown <= 0) {
        clearInterval(downloadTimer);
        console.log("time is up!");
      }
    }, 200, this);

  }
}

var t = new test
t.doit()

You could also use an arrow function to capture the value of this rather than passing it in:

class test {
  constructor() {
    this.countdown = 20
  }
  doit() {
    console.log(this.countdown); //i got data 10 sec
    let downloadTimer = setInterval(() => {
      this.countdown--; // how to update this.countdown ?
      console.log(this.countdown);
      if (this.countdown <= 0) {
        clearInterval(downloadTimer);
        console.log("time is up!");
      }
    }, 200);

  }
}

var t = new test
t.doit()

Upvotes: 2

Related Questions