当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

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

网友答案:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: