Callback function:

Passing a function as an argument to another function is a callback function

let callback = function(){   
	console.log('i am do homework')
}
function doWork(cb) {    
	console.log('start do work')    
	cb()    
	console.log('end do work')
}
doWork(callback)

Copy the code

Synchronous callback:

The callback function is executed before the main function doWork returns. As in the above code.

Asynchronous callback:

The callback function is not called inside the main function doWork, and is called an asynchronous callback when the callback is performed outside the main function

// 通过setTimeout函数让callback在doWork函数执行结束后并延迟1s执行
let callback = function() {
    console.log("i an do homework")
}
function doWork(cb) {
    console.log("start do work")
    setTImeout(cb, 1000)
    console.log("end do work")
}
doWork(callback)
Copy the code

The difference between synchronous and asynchronous callbacks (from a message loop perspective) :

The message queue and main thread loop mechanism ensures that pages run smoothly

  • A synchronous callback is executed in the context of the current main function
  • An asynchronous callback is when the callback function executes outside of the main function. Generally, there are two ways:
    • Make the asynchronous function a task and add it to the end of the message queue
    • Add asynchronous functions to the microtask queue so that the microtask can be executed at the end of the current task.

XMLHTTPRequest execution mechanism (from the perspective of the loop system) :

Step 1: Create the XMLHTTPRequest object

Step 2: Register the callback function for the XHR object

Step 3: Configure the basic request information

Step 4: Initiate the request

“Pit” in XMLHTTPRequest usage

  • Cross-domain problem
  • HTTPS mixed content issues

In contrast, setTimeout directly adds the delayed task to the delay queue, while XMLHttpRequest initiates the request, which is executed by other processes or threads of the browser. The renderer is then notified of the execution result via IPC, and the renderer adds the corresponding message to the message queue