最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add delay between two functions in reactjs - Stack Overflow

programmeradmin1浏览0评论

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

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");
Share Improve this question edited Jul 26, 2018 at 20:33 Mr.cysl asked Jul 26, 2018 at 18:37 Mr.cyslMr.cysl 1,6348 gold badges25 silver badges44 bronze badges 10
  • Probably setTimeout? – The Reason Commented Jul 26, 2018 at 18:39
  • a(); setTimeout(() => {console.log("delayed"); b()}, 100);?? – Ashish Ranjan Commented Jul 26, 2018 at 18:39
  • retrying........ – Mr.cysl Commented Jul 26, 2018 at 18:40
  • Do you want to finish the execution of a() then wait for 100ms and then call b()?? – Ashish Ranjan Commented Jul 26, 2018 at 18:43
  • You know that using setTimeout is a bad practice... – Oleksii Commented Jul 26, 2018 at 18:43
 |  Show 5 more ments

3 Answers 3

Reset to default 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

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

Try this:

a() // First call function a

Then call function b in setTimeout function.

es5:

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

es6:

setTimeout(()=> {b()},100); 
发布评论

评论列表(0)

  1. 暂无评论