Simulating Async Operations

setTimeout()

  • .setTimeout() function, available both in Node.js and in browsers, waits a given number of milliseconds (1 sec = 1000 ms) and then calls a function

  • .setTimeout() takes two parameters:

    • A callback function (remember callbacks are just functions passed in as parameters)

    • The number of seconds after which the method will be called

  • .setTimeout() is async by default; this is the primary reason it’s often used to simulate asynchronous operations


Example

const delayedGreeting = () => {
  console.log('Hi, sorry for the wait!')
}

/*
 call setTimout(), it accepts 2 parameters
 1. callback (function to be executed)
 2. delay in milliseconds (1000 ms = 1 sec)
*/

console.log('calling .setTimeout()')
setTimeout(delayedGreeting, 3000)
console.log('end of the code')

In the code above, .setTimeout() is used to delay the execution of the .delayedGreeting() function by 3 seconds.

  • Run the example in the jsbin below and notice how the message: end of the code is executed before the Hi, sorry for the wait!.

JS Bin on jsbin.com

  • This means that our program did not wait for .delayedGreeting() to finishing running before it executed

Event Loop

  • Asynchronous JavaScript uses something called the event-loop

  • In the example above, After 3 seconds, .delayedGreeting() is added to a line of code (Event Queue) waiting to be run

  • Before it can run, any synchronous code from the program will run first (from the Call Stack)

  • Next, any code in front of it in the line will run

  • This means it might be more than two seconds before delayedHello() is actually executed

inline