Understanding JavaScript Timer Stream Issues

I start with javascript MMORPG, which will work fine. Currently, I have created a demo to prove that I can move characters and communicate with them with each other, as well as see how each other moves live.

http://set.rentfox.net/

Now Javascript timers are something that I have not used widely, but from what I know, correct me if I am wrong, is that running multiple setIntervals at the same time does not work b / c very well. one thread.

Suppose I wanted 10 different people to fire fireballs at a monster using a positional focal position using setInterval - for this animation, 10 setIntervals would be needed to redraw the DOM to offset the background coordinates of the sprite. Wouldn't that be a big mistake?

I was wondering if there is a way around this, possibly using Canvas, so the animation can happen simultaneously without creating an event queue, and I don't need to worry about timers.

Hope this makes sense, and please let me know if I need to clarify.

+7
javascript javascript-events timer settimeout setinterval
source share
2 answers

The problem with multiple setInterval binary. The first, as you indicate, since all Javascript in the browsers (currently) is single-threaded, a single timer execution may pause the execution of the next timer. ( Workflows , however, Firefox already has them , like Safari 4 [and possibly others].) Secondly, the timer runs at a given interval, but if your handler still works when this interval expires, the second interval is fully skipped. For example, a timer may interfere with itself.

This last part needs further explanation. Let's say you have a setInterval of 10 ms (which is the fastest, when you can reasonably expect that any implementation will do this, it can be clamped so that they don't advance faster). If your handler takes 13 ms, the interval that was supposed to happen 10 ms after it started will be completely skipped.

I usually use setTimeout for this kind of thing. When my handler starts, I do my work and then schedule the next event at the end of the handler. Then (to the extent that you can be sure), I know that the next event will happen in this interval.

For what you are doing, it seems that one “pulse” timer would be best when working on what it needs to do on the pulse. Regardless of whether this pulse timer uses a setInterval or setTimeout call based on what you see with your actual code.

+11
source share

+1 to T.J. Crowder, the answer was perfect. I highly recommend learning to use Canvas on top of DOM nodes for game animation; the latter is slow and buggy, and it will hang the browser in any non-trivial situation. OTOH, Canvas is much faster and can be hardware accelerated and even has a 3D context if you need it.

+3
source share

All Articles