Home >Web Front-end >JS Tutorial >How Can I Effectively Call Asynchronous JavaScript Functions Without Blocking the UI?
Calling Asynchronous JavaScript Functions Synchronously
Your requirement to make asynchronous calls synchronous without freezing the UI presents a unique and challenging problem. Unfortunately, blocking JavaScript execution without halting the UI is not feasible.
One potential solution involves using global variables for data exchange. The callback from the asynchronous call can modify a global variable containing the desired data. Meanwhile, a polling mechanism checks the global variable at regular intervals until the data becomes available.
function doSomething() { window.data = null; // Clear global data myAsynchronousCall(param1, callBack); var intvl = setInterval(function() { if (window.data) { clearInterval(intvl); console.log(window.data); } }, 100); } function callBack(d) { window.data = d; }
However, a more suitable solution, given the example you provided, would be to follow best practices and pass a callback function to doSomething():
function doSomething(func) { function callBack(d) { func(d); } myAsynchronousCall(param1, callBack); } doSomething(function(data) { console.log(data); });
By passing a function to doSomething(), you can correctly utilize asynchronous calls without resorting to questionable techniques.
The above is the detailed content of How Can I Effectively Call Asynchronous JavaScript Functions Without Blocking the UI?. For more information, please follow other related articles on the PHP Chinese website!