views:

50

answers:

3

I want to lock other threads when one thread is running. It is possible in .Net with a lock object. I need do the same in AJAX.

    function f_OrnekleriGetir(bKaydet) {

        var ddlKlinikId = "<%=ddlKliniklker.ClientID%>";
        var iKlinikId = $("#" + ddlKlinikId + " option:selected").val();
        var arrOrnekNolar = new Array();
        $(".tdOrnekNo").each(function(idx, td) {
            var sOrnekNo = $(td).html();
            arrOrnekNolar[idx] = sOrnekNo;
        });

        for (var i = 0; i < arrOrnekNolar.length; i++) {

                // i want to wait in here...
                f_OrnekGetirKaydet(arrOrnekNolar[i], iKlinikId, bKaydet);   
            }
        }
    }

Is it possible?

KR,

Çağın

+1  A: 

You can't do multithreading in javascript. It's all single-threaded.

Tim
I think he means ajax requests, IE you can send and wait for multiple requests
Tom Gullen
I gather that, but it's still single-threaded. AJAX callbacks all happen on the same thread, so locking shouldn't be necessary.
Tim
A: 

I'm not sure if you can lock threads in Javascript, but I think it boils down to a design issue. Threads are supposed to be run for processes that can run in parallel. If you want a thread to wait for a response from another thread, then you're looking at the issue incorrectly.

Either way, have you investigated Web Workers?

MunkiPhD
+2  A: 

You can "lock" the main thread with a loop. There's a few major downsides here, though.

  • JavaScript runs on the browser's UI thread. This means the page's UI is locked up until the currently executing JavaScript completes, blocking user interaction and rendering.
  • Some browsers will detect a script that takes a long time to complete and ask the user if they want to stop running it.
  • The operating system might ask the user if they want to close the browser if it's not responding.
  • Without a solid break; clause, you could get stuck in an infinite loop. Remember that no other code will execute (not even callbacks) until you break out of the loop. The only properties that will change are those that change asynchronously, like the readyState property.

If you want to lock the thread whilst waiting for an Ajax request, you could send the request synchronously. This will have the same downsides as the blocking loop, however.

As MunkiPhD said, you're probably looking at the issue incorrectly. Callbacks are widely used in JavaScript to avoid blocking the UI thread, it's almost guaranteed that structuring your code to use a callback function on either a timer or an event will work much better than what you currently have in mind.

Andy E
I put $.ajaxSetup({ async: false }); before my ajax call. And problem solved. Thanks for your explains and suggestions.
cagin