Let’s see an example of this below:
/*
Modify printLetter() to make it an async function
by using .setTimeout
After the changes, the letter will be print at a random interval from
0 seconds to 3 seconds
*/
function printLetter(letter) {
setTimeout(() => {
console.log(letter)
}, Math.floor(Math.random() * 3000))
}
function printAll(){
printLetter("A")
printLetter("B")
printLetter("C")
}
console.log('Calling printAll function')
printAll()
console.log('End of code')
In the code example above we have turned .printLetter()
into an asynchronous function through the use of .setTimeout
to randomly delay each function call from anywhere between 0 seconds and 3 seconds
Run the jsbin below (multiple times) and notice how the order of the printed letters is no longer predictable and that A, B, and C print in a different and random order each time you call printAll