JQuery loop blocking site (socket.io data)

I am using socket.io to send data to the browser to update the status of other members (ex: online / offline / not / busy).

I find when data arrives (every 10 seconds) to process the page it hangs for a moment. For example: the browser's scrollbar (if you move it up / down) will stop for a moment and won't respond.

I don't believe the problem is with websockets, because if I don't process the data (for example, it's still coming to the browser) the browser doesn't freeze. it only hangs while processing data.

below is the loop I am using to process the data:

I know that I could better target the items to be updated rather than using generic search (and I will), but I'm still very surprised that this code causes the site to freeze momentarily when used.

The posted data will contain about 100 user / status updates, so I guess it will go through this about 100 times and have to look up the DOM 100 times. Is this the reason it hangs? Wouldn't that handle this in the background?

I guess I'm trying to figure out why the hang is happening. I have used jQuery a lot and have never encountered such a hang. Any tips / ideas would be greatly appreciated.

+3


source to share


1 answer


Javascript in the browser is single threaded. So only one Javascript stream is running at a time. If you have code that is busy handling incoming WebSocket messages, then other Javascript cannot work until that code is executed.

Javascript does this by ordering everything through an event queue . When one piece of Javascript ends, then the JS engine pulls the next event from the event queue and fires it.



If your page appears for a short time when an incoming message arrives, it might be because your Javascript that processes this incoming message is taking too long and makes other interactivity on the page, wait until that processing is done ... A better solution would be to improve the performance of the code that processes these incoming messages so that it is fast enough that there is no noticeable impact on the interactivity of the page.

There is no general way to speed up your code - what makes the most difference depends entirely on the specific code, how it is written and what it is trying to accomplish. Thus, you can get more specific recommendations for improving the code if you show us the actual code and describe what it needs to be done. Doing something 100 times in a row means that each operation must be very, very fast (less than a couple of milliseconds per operation) if you don't want to notice the cumulative delay from doing 100 of them.

0


source







All Articles