Home > Software design >  I am using setTimeout and fetch API both, bot didn't understand which one will execute first?
I am using setTimeout and fetch API both, bot didn't understand which one will execute first?

Time:09-17

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => console.log(json))

setTimeout(()=>{
  console.log("Callback after delay")
},1000)

setTimeout(()=>{
  console.log("Callback with no delay")
})

console.log("HI this is test")

It is giving the below output:

HI this is test
Callback with no delay
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
Callback with delay

As callback in promises goes to microtask queue then callback in fetch should be execute first and after that setTimeout code with no delay and then delay

CodePudding user response:

as @Andy mentioned, The fetch and setTimeout are asynchronous, and will execute when it finished, so for example if the fetch method took more than one second to get the data it will execute after the setTimeout after delay.

If you want the fetch method execute first and then the setTimeout you need to await it.

(async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
  const result = await response.json();
  setTimeout(()=>{
    console.log("Callback after delay")
  },1000)

  setTimeout(()=>{
    console.log("Callback with no delay")
  })

  console.log("HI this is test")
 
})

Now the fetch will execute the first one.

CodePudding user response:

fetch, setTimeout both runs asynchronously.

The difference is that --

There is no guaranteed time when the response will come back from fetch. The code in then will execute when the response is received (when the Promise is resolved).

However, in case of setTimeout, you provide the timeout. The internal Web APIs of the browser runs a timer of the given duration (milliseconds). After the timer times out, your code will get executed. In your case you have two setTimeout - one with 0 ms, another 1000 ms. So, first you'll see "Callback with no delay", then after one second "Callback after delay".

console.log() runs like synchronous code. So the moment this line executed you'll see the "HI this is test" text on console.

You're seeing this order, because the fetch response came back before 1 second. The placement of fetch response will vary depending on the speed of the network, and response time from the server.

HI this is test
Callback with no delay
{userId: 1, id: 1, title: 'delectus aut autem', completed: false}
Callback with delay

However, these two messages will always be at the top in the same order:

HI this is test
Callback with no delay

I hope the explanation was clear!

  • Related