Mr.cysl
Mr.cysl

Reputation: 1614

Add delay between two functions in reactjs

I have two functions and I need a forced delay between those two consecutive function calls. That is to say,

a // call func a
delay(100) // delay for 100 ms
b // call func b

Is there anyway to do so?

Edit: tried

  a();
  console.log("a");
  setTimeout(b(), 1000);
  console.log("b");

Upvotes: 2

Views: 3458

Answers (3)

Shubham Khatri
Shubham Khatri

Reputation: 281764

All you need to do is to make use of setTimeout function to call b after calling a

a() // call func a
setTimeout(b, 100) // delay for 100 ms

if you need to keep b function bound to the current scope, use:

setTimeout(() => b(), 100) // () => {} functions are always bound to the current scope

Upvotes: 4

Syed Kashan Ali
Syed Kashan Ali

Reputation: 663

Try this:

a() // First call function a

Then call function b in setTimeout function.

es5:

setTimeout(function() {b()},100); 

es6:

setTimeout(()=> {b()},100); 

Upvotes: -1

Kamalakannan J
Kamalakannan J

Reputation: 2998

With new ES6, you can even make it more cleaner and look like sequential,

function delay(ms) {
   return new Promise((resolve) => {
      setTimeout(resolve, ms);
   })
}

async function doItHere() {
   console.log('a', Date.now());
   await delay(5000);
   console.log('b', Date.now())
}

doItHere();

Upvotes: 3

Related Questions