Jump to Categories

Async & Sync

Synchronous (Blocking)

The opposite of asynchronous. When clicking to load a regular webpage you then have to wait for the page to load before you can do anything else. This process is called synchronous as operations will only happen after the previous one is complete.

console.log('one');
countToAMillionAndSayYes();
console.log('two');
console.log('three');

// one
// yes
// two
// three


In the above examples the console will log one after another and even though the 'countToAMillionAndSayYes' function will take a while, the last two consoles have to wait for it to finish before they can execute.

Asynchronous

Also know as async, asynchronous is the opposite of synchronous. It doesn't wait for each operation to complete, instead it executes everything and then handles the operations once their results are available. By nature javascript is synchronous so you have to make use of API's - such as timeouts, Ajax, requestAnimationFrame etc - to perform async tasks.

console.log('one');
window.setTimeout(function() {
    console.log("two");
}, 1000);
console.log('three');

// one
// three
// two


In this example - from Bergi on Stack Overflow - the operations run one after another, but when the browser encounters the setTimeout it fires it, but carries on executing the rest of the code until it has returned a result and is ready to be console.logged.