JavaScript - - By Craig Buckler

JavaScript Execution and Browser Limits

The browser UI and JavaScript code (effectively*) share a single processing thread. It doesn’t matter whether the browser needs to respond to its own menu click, render an HTML page or execute your Ajax call — every event is added to a single queue. When the browser becomes idle, the next item on it’s to-do list is retrieved and executed.

note: Single Browser Threads

In reality, no modern browser operates on a single thread. As an extreme example, IE9 and Chrome start a new OS process for every tab. However, there is still a single event queue per viewed page and only one task can be completed at a time. This is absolutely necessary because the browser or your JavaScript can alter the rendered HTML before, during or after it’s downloaded.

Understandably, the browser must limit the time it takes for your JavaScript code to run. If a script takes too long, it will lock the application and potentially cause OS instability. It’s the reason you’ll see the dreaded “Unresponsive Script” alert:

Unresponsive Script

But how does a browser determine when a script has run for too long? As you’d expect, the top 5 vendors implement different techniques and limits…

Internet Explorer
IE limits JavaScript execution to 5 million statements.

Firefox
Firefox uses a timed limit of 10 seconds.

Safari
Safari uses a timed limit of 5 seconds.

Chrome
Chrome does not limit execution but detects when the browser crashes or becomes unresponsive.

Opera
Opera does not implement a limit and will execute JavaScript indefinitely. However, the browser will not cause system instability — you can continue to open other tabs or close the page executing the code.

Several of the browsers allow you to configure the execution limit parameters, but that’s not something I’d recommend. I won’t publish the details here because someone, somewhere will use it as a “fix” for their unresponsive page! Google it if you like, but tweaking browser settings for badly-behaved code does not address the root of the problem.

So how can we prevent JavaScript execution alerts? The best solution is to avoid long-running client-side tasks. Ideally, no event handler should take longer than a few dozen milliseconds. Intensive processing jobs should normally be handled by the server and retrieved with a page refresh or an Ajax call.

However, I’m conscious that minimizing client-side processing is not necessarily a viable solution for today’s JavaScript-heavy applications. Fortunately, there are a number of solutions … stay tuned to SitePoint for several alternatives coming soon.

note:Want more?

If you want to read more from Craig, subscribe to our weekly tech geek newsletter, Tech Times.

Sponsors