Monday, 1 May 2023

Examples of synchronous and asynchronous code in JS

1. Using Synchronous

The program waits for the current task to finish before starting the next task

// code
console.log('start');
function run() {
console.log('before');
setTimeout(function() {console.log('wait 3 seconds')}, 3000);
console.log('after');
}

run();

console.log('end');

output

start
before
after
end
wait 3 seconds

2. Using Asynchronous 

The program can continue to execute while waiting for a task to complete

// code 
console.log('start');
async function run() {
console.log('before');
await setTimeout(function() {console.log('wait 3 seconds')}, 3000);
console.log('after');
}

run();

console.log('end');

output

start
before
end
after
wait 3 seconds

Thank you 


No comments:

Post a Comment

Golang Advanced Interview Q&A