2

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");
10
  • Probably setTimeout? Commented Jul 26, 2018 at 18:39
  • a(); setTimeout(() => {console.log("delayed"); b()}, 100);?? Commented Jul 26, 2018 at 18:39
  • retrying........ Commented Jul 26, 2018 at 18:40
  • Do you want to finish the execution of a() then wait for 100ms and then call b()?? Commented Jul 26, 2018 at 18:43
  • You know that using setTimeout is a bad practice... Commented Jul 26, 2018 at 18:43

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

6 Comments

@IsaacFerreira @Li357 the benefit to wraping in an inline function is that the proper this is kept without explicit binding
Thanks for the reply. However, I tried this and that does not seem to be working. I edited the question to show what I did, could you take a look?
In this case, this is useless, once it's just a calling.
@Li357 it's not my answer and I'm one of the two upvotes on Isaac Ferreira's comment. I understand that it's not necessary here, but if the OP doesn't even know how to use a timeout, they probably would have no idea what to do when they use this on a function that DOES need scope and it comes out wrong
setTimeout expects the first parameter as the function that it will execute and hence setTimeout(b(), 1000); isn't the correct syntax
|
3

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();

Comments

-1

Try this:

a() // First call function a

Then call function b in setTimeout function.

es5:

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

es6:

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

1 Comment

No. Unless b returns a function, this will just immediately call b

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.