开发者

How can I lock threads in Javascript?

开发者 https://www.devze.com 2023-01-13 15:39 出处:网络
I want to lock other threads when one thread is running. It is possible in .Net with a lock object.I need do the s开发者_如何学JAVAame in AJAX.

I want to lock other threads when one thread is running. It is possible in .Net with a lock object. I need do the s开发者_如何学JAVAame 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


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.


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


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消