Heinrich Schmetterling
Heinrich Schmetterling

Reputation: 6884

Browser freezes during javascript eval()

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?

Upvotes: 0

Views: 831

Answers (3)

Chad Johnson
Chad Johnson

Reputation: 21895

You may also try executing the code by injecting a new script tag into the page:

function executeCode(code) {
    var element = document.createElement('script');
    element.type = 'text/javascript';

    try {
        element.appendChild(document.createTextNode(code));
        document.body.appendChild(element);
    }
    catch (e) {
        element.text = code;
        document.body.appendChild(element);
    }
}

var code = 'alert("hello world");';
executeCode(code);

Upvotes: 1

Georg Schölly
Georg Schölly

Reputation: 126105

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.

Upvotes: 0

Annie
Annie

Reputation: 6631

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)

Upvotes: 4

Related Questions