简体   繁体   English

如何在使用 setTimeout() 时使用不同的 arguments 按顺序调用相同的 function

[英]How to call the same function sequentially with different arguments while using setTimeout()

I would like to call the function example multiple times with different arguments, while using setTimeout inside logic .我想用不同的 arguments 多次调用 function example ,同时在logic中使用setTimeout I want this to be sequential (after the first call is made and finished, the second call can begin, and so on).我希望这是顺序的(在第一个调用完成后,第二个调用可以开始,依此类推)。 In the following code snippet, example seems to be going through both arrays element-wise:在下面的代码片段中, example似乎同时通过了 arrays 元素:

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

function logic(i, arr) {
    setTimeout(() => {
        console.log(arr[i]);
    }, (i + 1) * 300);
}

function example(arr) {

    for (var i = 0; i < arr.length; i++) {

        logic(i, arr);
    }

}

setTimeout(() => {
    example(arr1)
}, 3000);
setTimeout(() => {
    example(arr2)
}, 3000);
1
4
2
5
3
6

I am aware that I could just set the timer of the second call to 6 seconds for example, and it will work, but I wonder:我知道我可以将第二次调用的计时器设置为例如 6 秒,它会起作用,但我想知道:

Is there is another way to find out that the call to example is done and then trigger the next one?是否有另一种方法可以发现对example的调用已完成,然后触发下一个? Without statically defining some delays and maybe even without setTimeout ?没有静态定义一些延迟,甚至可能没有setTimeout

The expected output would be:预期的 output 将是:

1
2
3
4
5
6

logic needs to let the caller know when it's done, then example needs to let the caller know when it's done. logic需要让调用者知道它何时完成,然后示例需要让调用者知道它何时完成。 Promises will help you here.承诺会在这里帮助你。

let arr1 = [1, 2, 3];
let arr2 = [4, 5, 6];

function logic(i, arr) {
  return new Promise(resolve => {
    setTimeout(() => {
        console.log(arr[i]);
        resolve();
    }, (i + 1) * 300);
  });
}

async function example(arr) {

    for (var i = 0; i < arr.length; i++) {

        await logic(i, arr);
    }

}

(async function() {
  await example(arr1);
  await example(arr2);
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM