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

Is there a way to optimise this:function run1 () {console.log("Hello");}function run2 () {c

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744316066a4568188.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信