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

javascript - Use lodash to trigger two functions when setTimeout is executed - Stack Overflow

programmeradmin3浏览0评论

Is there a way to optimise this:

function run1 () {
  console.log("Hello");
}
function run2 () {
  console.log("World");
}
function timeoutComplete () {
  run1();
  run2();
}
setTimeout(timeoutComplete, 1000);

Like this, so that I don't need to declare timeoutComplete...?

setTimeout(_.xyz(run1, run2), 1000);

Is there a way to optimise this:

function run1 () {
  console.log("Hello");
}
function run2 () {
  console.log("World");
}
function timeoutComplete () {
  run1();
  run2();
}
setTimeout(timeoutComplete, 1000);

Like this, so that I don't need to declare timeoutComplete...?

setTimeout(_.xyz(run1, run2), 1000);
Share Improve this question asked Aug 16, 2016 at 20:28 ngDeveloperngDeveloper 1,3042 gold badges17 silver badges35 bronze badges 9
  • @Vld, I think _.pose is right-to-left. But _.flow is left-to-right, so maybe _.flow(run1, run2), right? – ngDeveloper Commented Aug 16, 2016 at 20:33
  • I guess if you want left-to-right, then flow. I wasn't aware of it - I was going off the Underscore API - it only has pose. – VLAZ Commented Aug 16, 2016 at 20:37
  • @Vld lodash doesn't have pose function. – Ram Commented Aug 16, 2016 at 20:39
  • These also invokes the functions with the return value of the previous function as argument to the next, right? (Not that it matters in this specific case...) – koster1889 Commented Aug 16, 2016 at 20:40
  • @Vohuman my Underscore knowledge lets me down, then. Apparently, it's flowRight in lodash. Which is odd - I thought lodash was patible with Underscore's API. Anyway, it's the same concept anyway, only lodash has bizarrely renamed it for some reason. – VLAZ Commented Aug 16, 2016 at 20:42
 |  Show 4 more ments

4 Answers 4

Reset to default 4

You can use delay() and flow():

_.delay(_.flow(run1, run2), 1000);

The main advantage of delay() over setTimeout() is that it can pass arguments to the callback if need be.

You can always just use an anonymous function in the timeout and call them there:

setTimeout(function() {
    run1(); 
    run2();
});

You could use an anonymous function instead:

setTimeout(function() {
  run1();
  run2();
}, 1000);

Write _.xyz yourself, except it doesn't need to be a lodash function:

function run(...fns) {
  return function() {
    fns.forEach(fn => fn());
  };
}

setTimeout(run(run1, run2), 1000);
发布评论

评论列表(0)

  1. 暂无评论