I'm using eval() in javascript to evaluate a significant amount of js code (not just json, but function calls too). The browser freezes during the call, i.e. the user cannot scroll the browser or click anything. Is there any way around this freezing problem?
+4
A:
In most browsers, JavaScript runs on the UI thread, so it blocks the UI as you describe. The best way to un-block the UI is to break up the JS into smaller parts, and string them together with setTimeout (which gives control of the thread back to the browser for UI rendering)
Annie
2010-01-04 22:54:46
A:
You have to break up your function into smaller parts. I recommend combining them with setTimeout
.
In modern browsers there are web workers that can compute data in the background.
Georg
2010-01-04 23:04:18
Does the UI rendering resume after each line of code within setTimeout?Why doesn't the freezing happen when, say, the browser executes a large amount of javascript when loading an initial page?
Heinrich Schmetterling
2010-01-04 23:11:34
That depends on the browser. I believe that the UI freezes only if it's either a) maxing out the CPU b) the javascript manipulates the HTML/CSS. You should do your own testing, I haven't got _any_ data to support my claim.
Georg
2010-01-04 23:15:00
The UI *does* block when JavaScript is executed when loading an initial page. Most JavaScript doesn't take that long to run though, so hopefully you don't notice it.
bobince
2010-01-04 23:43:56