4

I am building a countdown timer function in Angular that will keep executing every second. To call the function, I am using setInterval. This will be used in a mobile app (Ionic).

setInterval(() => {
  this.countdownTime = this.getCountDownTime(date1,date2);
  console.log(this.countdownTime);
}, 1000);

Is this the correct way to update the time every second? Or, is there an efficient alternative?

Titulum
  • 9,928
  • 11
  • 41
  • 79
joler-botol
  • 442
  • 1
  • 7
  • 22
  • In my opinion your solution is correct. Your binding needs to be done to the countdownTime property and then everything is working correctly. Are there any problems in efficiency? – StyrianDev Jan 20 '20 at 11:51
  • As functionality it will give you what you want , but for performance reasons its bad since it causes the app to have much performance and thus will cause device over heating. If you could try to use a for loop statement that breaks after some time when reaches a specific value then restarts and keep on till you reach your desired purpose. – Mostafa Harb Jan 20 '20 at 11:55
  • Does this answer your question? [How to do a timer in Angular 5](https://stackoverflow.com/questions/50455347/how-to-do-a-timer-in-angular-5) – Titulum Jan 20 '20 at 11:56
  • @MostafaHarb, I do not agree. A simple setInterval that runs every second is not that CPU intensive, not will it cause overheats. Look at [this question](https://stackoverflow.com/questions/6650134/is-setinterval-cpu-intensive) for more information. – Titulum Jan 20 '20 at 11:58
  • He didn't say he want to stop the interval, he wants it to keep working all the time, and if it keeps so it will cause performance problems... – Mostafa Harb Jan 20 '20 at 12:01
  • Consider using rxjs interval / timer. I guess the "purest" angular way would be to build it with observables – C.OG Jan 20 '20 at 13:04

1 Answers1

2

What you are doing is correct. Just make sure to clear the interval using clearInterval when you want it to stop:

const delay = 1000;
let interval;

function start() {
  this.interval = setInterval(() => {
    this.countdownTime = this.getCountDownTime(date1,date2);
    console.log(this.countdownTime);
  }, delay);
}

function pause() {
  clearInterval(this.interval);
}

Titulum
  • 9,928
  • 11
  • 41
  • 79
  • 1
    But if I navigate to another component, will it be required to use clearInterval? – joler-botol Jan 20 '20 at 12:09
  • It depends, but that's probably the best solution. Check out [this question](https://stackoverflow.com/questions/37116619/angular-2-setinterval-keep-running-on-other-component) to find out how to do this. – Titulum Jan 20 '20 at 12:14