In JavaScript, synchronous code is executed in a single thread, meaning that only one task can be processed at a time. Synchronous code blocks the execution of other code until it completes. Asynchronous code, on the other hand, allows other code to be executed while waiting for a particular task to complete.
Here are some examples to illustrate the difference between synchronous and asynchronous JavaScript code:
Synchronous code:
console.log("Start");
function wait(ms) {
var start = new Date().getTime();
while (new Date().getTime() < start + ms);
}
wait(2000); // wait for 2 seconds
console.log("End");
In this example, the wait function blocks the execution of other code until it completes. The code logs "Start", waits for 2 seconds, and then logs "End".
Asynchronous code:
console.log("Start");
setTimeout(function() {
console.log("Hello, world!");
}, 2000);
console.log("End");
In this example, the setTimeout function allows other code to be executed while waiting for the specified delay to elapse. The code logs "Start", schedules the console.log("Hello, world!") function to be executed after 2 seconds, and then logs "End". After 2 seconds, the scheduled function is executed and logs "Hello, world!" to the console.
Another common example of asynchronous code in JavaScript is AJAX requests, which allow web pages to retrieve data from a server without blocking the execution of other code.
In summary, synchronous code in JavaScript blocks the execution of other code until it completes, while asynchronous code allows other code to be executed while waiting for a particular task to complete. Asynchronous code is commonly used for tasks that may take a long time to complete, such as network requests or user interactions.