Sam YC
Sam YC

Reputation: 11617

Javascript with multithreading?

I am coming from a desktop application background, when I am learning Javascript, it is really difficult to understand the threading mechanism in Javascript.

For example:

<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        for (var i = 0 ; i < 100000 ; i ++){
            $("#loop1").html(i);

        }
    });

    $("#btn2").click(function(){
        for (var i = 0 ; i < 100000 ; i ++){
            $("#loop2").html(i);

        }
    });
});
</script>
</head>
<body>

Loop 1 : <p id="loop1"></p>
<button id="btn1">Button 1</button>
<br/><br/><br/>

Loop 2 : <p id="loop2"></p>
<button id="btn2">Button 2</button>

</body>
</html>

When I click on the button 1, the browser hang, so button 2 will not be responsive when I click it. Usually in desktop application, I will post the looping into background thread. But how am I going to do that in Javascript? Or what is the best way in handling long processing in Javascript?


edited :

the code below does not work, but not sure why.

$("#btn1").click(function(){

        setTimeout( function(){
            for (var i = 0 ; i < 100000 ; i ++){
                $("#loop1").html(i);

            }
        }
        , 0);
    });

Upvotes: 0

Views: 213

Answers (3)

Tim S.
Tim S.

Reputation: 13843

As previous answers already stated, WebWorkers are Javascript's only option for multi-threading. Unfortunately, there's no hope if you want to do DOM modifications.

What most people forget is when you call functions with setTimeout and setInterval the UI does not freeze and still receives updates.

function btnClickHandler() {
    setTimeout(doStuff, 1); // prevent UI freeze
}

function doStuff() {
    // do your stuff here
}

In your case:

var i, interval;

$("#btn1").click(function(){
    i = 0; // reset i

    // create interval
    interval = setInterval(btn1Handler, 1); // run btn1Handler every 1ms
});

function btn1Handler() {
    $("#loop1").html(i);

    if(i++ >= 100000) {
        // cancel the interval
        clearInterval(interval);
    }
}

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

Apart if you use web workers (and they can't directly change the DOM), there is only one user javascript thread in your browser.

Events are stacked until your function returns. You can'd have two long running operations changing the DOM in parallel.

Upvotes: 0

Gui13
Gui13

Reputation: 13551

There is NO multithreading natively in Javascript.

Some techniques try to implement multi threads in the HTML5 spec (WebWorkers), others try to implement it in javascript itself, but the base spec (ECMA) is single threaded.

You could just have searched on Google..

Upvotes: 2

Related Questions