I’m working on some projects and I was wondering why the setTimeout(s) I was delaying where taking a lot longer then expected…
To give a context, the code reacts to some triggers, and the function fires quite a lot (maybe like 15 times a second). on this function, I increment a global value, then do a setTimeout of 3 seconds and decrement the global value by the same amount (expecting it to be back to 0 after the maximum 3 seconds every timeout should take)
But apparently they have a way of working different from what I expected, and they sort of stack in time… so the global value decrement slowly.
code :
//trigger method... just fires like a button press in html
register("soundPlay", () => {
addCount();
}).setCriteria("random.successful_hit");
var count = 0;
function addCount() {
console.log("triggered");
count+= 10;
setTimeout(function () {
count-= 10;
}, 3000);
}
Here’s a result of the function after I stop triggering, the stacking is shown in the brackets. It shows every 1/20th of a second. So from the moment I stop it takes over 30 seconds to get down to zero.
Any ideas why? Any solutions or reason?
Ty 🙂
2
Answers
You have to use debounce to get the effect you want
Your code works fine for me