I understand the differences between setTimeout and setInterval, as this explained it quite nicely.
This question is about best practice when using timers, specifically setTimeout vs setInterval.
If I need to call a countdown several times in a game fairly frequently (for example, a player moves to a new location, which triggers a new countdown which will encourage them to move in 5 seconds), but it's not necessarily uniform intervals (meaning, they should move to next location, but can hang out at current location and be penalized), is it better performance-wise, and clean code-wise to:
a) keep clearing and setting setTimeout()
when the player decides to change location
if (player.newLocation !== player.oldLocation) { //player location has changed
window.clearTimeout(myTimer);
myTimer = setTimeout(function() {
do something
},50);
}
b) keep setInterval running, but change a variable that acts as that countdown each time the player moves to a new location
var counter = 0;
if (player.newLocation !== player.oldLocation) {
counter = 100;
}
myTimer = setInterval(function() {
if (counter > 0) {
// do something...
counter--;
}
},50);