1

I have multiple timers on a single page which are being started by ajax updates. Every interval has its own name assigned to the username of players. I want to top all timers when the game ends:

This is how intervals are being created: findNewPlayer() is being called on some events in the game:

function findNewPlayer(){
    $.ajax({
        url:"check.php",
        success:function(data){newTimer(data)}
    })
}

function newTimer(username){
 var username=setInterval(function() {startTimer()}, 1000);
}

function startTimer(){
    //blah blah
}

Now I want to stop all timers and restart the game with current players. How can I use clearInterval on a series of usernames which are not generated in an array? I know if they were array I could do the following but I want to find a way to get collection of all timers with different names in a window.

for (i = 0; i < interValArray.length; i++) {
    clearInterval(interValArray[i]);
}
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82

1 Answers1

1

You can maintain an array to hold the ID returned by the setTimeout call, then loop over the array on reset:

const timerIds = [];

function newTimer(username){
 timerIds.push(setInterval(function() {startTimer()}, 1000));
}

When you reset and start with new players, you need to clear the timers:

timerIds.forEach(clearInterval);
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
  • Thank you. Is there any reason that you used const instead of var? – Ali Sheikhpour Aug 13 '19 at 13:48
  • 1
    @AliSheikhpour as per the best practices it is recommended to always use `const` and make the array reference a constant so that later you don't accidentally overwrite it, now unless you really have a very urgent reason to change the reference later then you should go for `let/var `. This [answer](https://stackoverflow.com/a/22939592/3888766) would also help you to know why. Although the array reference becomes a constant using `const` but the array itself is still pretty much mutable and additions/deletions can be made. – Fullstack Guy Aug 13 '19 at 13:49