1

I have wrapped the long running logic(longLoop) with setTimeout function, but still UI become unresponsive until long running execcution over. It doesn't allow to click other UI button. Please look at my below example and let me know if any issue you see.

function longLoop () {
    var startLogTime, endLogTime;
    startLogTime = new Date().getTime();
    console.log("loop begin");
    for (var i = 0; i <= 500000000; i++) {
        var j = 10;
    }
    endLogTime = new Date().getTime();
    console.log("loop execution takes " + (endLogTime - startLogTime) + " milliseconds");
}

$(document).ready(function () {

    $("#btnButton").bind("click", function () {
        setTimeout(longLoop, 15);

    });

    $("#anotherButton").bind("click", function () {
        console.log("another operation clicked");
    });
});

<input type="button" id="btnButton" value="Start Long Operation" />
<input type ="button" id="anotherButton" value= "Another operation" />

Thanks

user845392
  • 563
  • 2
  • 8
  • 16
  • JavaScript is "single-threaded". Pretty sure `setTimeout` doesn't make its own "thread" when it runs, it just runs at a later point. – gen_Eric May 15 '12 at 19:10

3 Answers3

6

Even though it's "asynchronous", setTimeout still dispatches its calls on the main event loop. Since the main event loop also receives clicks, keyboard input, and every single event a webpage might dispatch, you're just delaying the moment at which your long operation freezes the UI.

If you want to run your operation in parallel to the main event loop, you should look into Web workers, which spawn real threads (with some important constraints).

Victor
  • 63
  • 6
zneak
  • 134,922
  • 42
  • 253
  • 328
0

JavaScript is single-threaded, so there is always exactly one method running. Once longLoop started, nothing else can be done. You can circumvent this limitation by using the new HTML5 web workers.

Manuel Leuenberger
  • 2,327
  • 3
  • 21
  • 27
0

JavaScript is not a mutithreaded language, even when you use setTimeout, it's running in the main thread, you are just postponing the operation, you should take a look at Web-Workers, the new JavaScript API for running cpu intensive tasks in the background

Community
  • 1
  • 1
Kamyar Nazeri
  • 25,786
  • 15
  • 50
  • 87