Synchronous:
- In synchronous operations tasks are performed one at a time and only when one
is completed, the following is unblocked. In other words, you need to wait for a
task to finish to move to the next one.
Asynchronous:
- In asynchronous operations, you can move to another task
before the previous one finishes.
Synchronous: In synchronous operations tasks are performed one at a time and only when one
is completed, the following is unblocked. In other words, you need to wait for a
task to finish to move to the next one.
function getUsername(callback) {
setTimeout(() => {
console.log("Alextz")
callback()
}, 2000)
}
getUsername(() => console.log("getUsername callback called"))
Asynchronous: In asynchronous operations, you can move to another task
before the previous one finishes.
function getUser(callback) {
setTimeout(() => {
console.log("Alextz")
}, 2000)
// get executed even though the user has not printed yet
callback()
}
getUser(() => console.log("getUser callback called"))
var btn = document.getElementById("btn");
btn.addEventListener("click", handler, false);
function handler(e) {
console.log("handler triggered");
doSomething();
console.log("handler done");
}
function doSomething() {
doThis();
doThat();
doTheOther();
}
function doThis() {
console.log("doThis - start & end");
}
function doThat() {
console.log("doThat - start");
// do something that takes a while
var stop = Date.now() + 1000;
while (Date.now() < stop) {
// wait
}
console.log("doThat - end");
}
function doTheOther() {
console.log("doThat - start & end");
}