Home >Web Front-end >JS Tutorial >How to \'Synchronize\' Asynchronous Javascript Calls?

How to \'Synchronize\' Asynchronous Javascript Calls?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 13:50:02963browse

How to

Synchronizing Asynchronous JavaScript Calls

Introduction

Asynchronous JavaScript functions allow us to perform tasks concurrently without blocking the main thread. However, in certain scenarios, it may be necessary to call an asynchronous function synchronously, effectively blocking the current execution until the task is complete.

Implementation

Contrary to popular belief, it is impossible to truly block JavaScript execution asynchronously without affecting the UI. One approach to simulate blocking is to poll a global variable, waiting for it to be set by the callback function.

function doSomething() {

  // Global variable for callback data
  window.data = null;

  function callBack(d) {
    window.data = d;
  }

  // Start asynchronous call
  myAsynchronousCall(param1, callBack);

  // Start polling interval
  var intvl = setInterval(function() {
    if (window.data) {
      clearInterval(intvl);
      console.log(data);
    }
  }, 100);
}

While this method achieves a semi-blocking behavior, it is not ideal as it can lead to significant performance overhead.

Preferred Solution

If possible, it is preferable to pass a callback function to the asynchronous call and have it handle the result when ready:

function doSomething(func) {

  function callBack(d) {
    func(d);
  }

  myAsynchronousCall(param1, callBack);
}

doSomething(function(data) {
  console.log(data);
});

This approach avoids the polling overhead and allows for more efficient asynchronous processing.

The above is the detailed content of How to \'Synchronize\' Asynchronous Javascript Calls?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn