Reputation: 353
I'm messing around with a game idea, just for fun, and I'm doing it in html5's canvas and javascript, simply because I want the practice while I'm fooling around.
In my game there are many things that will happen one at varying times, and new things to do are constantly created. Precision is not necessary, as long as it's within a few seconds.
My first idea was simply to have an array, who was manually sorted, by inserting the new tasks based on their execution time, I would then have a function set on a timeout, it would grab the new task, handle it, get the time of the next ask in line, and wait with a timeout, when a new item is added it would check to see if it was the new first in line, and change the timeout appropriately.
But then I began to wonder.... What would be the pitfalls of setting many timers? At first I had thought it'd be a bad idea to set many timers, but then I began to wonder if maybe the browser handles the times in the same way I stated above, or some other effecient way.
So basically, to summarize my concerns:
Upvotes: 3
Views: 4968
Reputation: 8808
Setting multiple timeouts will not affect you performance, so you should stop worry about that. Node.js internally handles timeouts in a similar manner to yours idea. If you want to see some example, look at the following snippet:
let count = 10000;
console.time('Total time')
for (let i = 0; i < count; ++i) {
setTimeout(() => {
if (--count === 0) {
console.timeEnd('Total time')
}
}, i / 10); // Set 10 timeouts for each millisecond
}
Ideally it's execution should take exactly 1000ms, as you can see, real result is not far from this.
Upvotes: 3
Reputation: 156
Off the top of my head, one thing you should keep in mind is that one timeout is one variable you have to assign. Should you want to cancel that timeout before it fires, you'll need to clearTimeout() with its handle. If you have many of them your code could become confusing to work with.
Moreover, Javascript is single threaded, so no actions can be executed at the same time. Sure it's fast enough to feel instantaneous, but having a stack order won't be any different.
At the end of the day it's your choice to code however you like best, so whether you choose to do one big global handling function or multiple small dedicated ones is up to you :)
Upvotes: 2