What is the difference between synchronous and asynchronous programming?
The difference between synchronous and asynchronous is the manner of execution. For example, in javascript, the execution of code goes from top to bottom in sequential order. Each item gets executed and continues to the next but not until the previous item has finished.
- Called one() .. 2 second execution time
- Called two() .. 4 second execution time (we must wait before the next method is called)
- Called three() .. 2 second execution time
Page data load: 8 seconds
However, you are able to run an asynchronous piece of code without the stack getting stuck. For example, an onclick event on a button tag would be considered asynchronous as it does not prevent execution of other code.
- Called one() .. 2 second execution
- Called two() .. 2 second execution time + 2 second wait on server background call (we don't need to wait in order for the next method to be called)
- Called three() .. 2 second execution time
- Asynced two() .. we are now able to use data from two()
Page data load: 6 seconds (saving 2 seconds from background async call)
The example below will show you a clear difference. Keep in mind, javascript has other asynchronous features in the form of promises.
HTML Source (non-advanced example, btw)
<!DOCTYPE html>
<html>
<head>
<title>Synchronous vs Asynchronous Example in Javascript</title>
</head>
<body>
<h1>Synchronous vs Asynchronous Example in Javascript</h1>
<h3>Synchronous</h3>
<div id="sync-data"></div>
<h3>Asynchronous</h3>
<div id="async-data"></div>
<button id="async-button">Async Click</button>
<script>
(() => {
let runCommand = (elementId, identifier, timeout = -1) => {
console.log('runCommand', elementId, identifier, timeout)
if (timeout > -1) {
console.log('Waiting for data...', identifier, timeout + ' second delay')
window.setTimeout(() => {
runCommand(elementId, identifier)
}, timeout * 1000)
} else {
let dataNode = document.createElement('div')
let textNode = document.createTextNode('Run method ' + identifier + ' was called')
dataNode.appendChild(textNode)
document.getElementById(elementId).appendChild(dataNode)
}
}
// @type sync
// @stack 1, 2, 3, 4
for (let i = 1; i <= 4; i++) {
runCommand('sync-data', i)
}
// @type async
// @stack 1, 2, 4, 3
runCommand('async-data', 1)
runCommand('async-data', 2)
runCommand('async-data', 3, 2) // call after 2 seconds, continue to call next tick
runCommand('async-data', 4)
// @type async
document.getElementById('async-button').addEventListener('click', () => {
console.log('async-button clicked')
let dataNode = document.createElement('div')
let textNode = document.createTextNode('Button was called without interruption of other async threads')
dataNode.appendChild(textNode)
document.getElementById('async-data').appendChild(dataNode)
})
})()
</script>
</body>
</html>
For more information on async/await in javascript, check out the animation in this article: Understanding Async/Await in 7 Seconds
Top comments (0)