gpt4 book ai didi

javascript - 如何编写一个函数 "inOrder"来接受两个回调并按顺序调用它们。

转载 作者:行者123 更新时间:2023-12-01 02:15:42 25 4
gpt4 key购买 nike

如何使用回调模式和 Promises 实现“inOrder”。

var logOne = setTimeout(function() {
console.log("one!");
}, Math.random() * 1000);

var logTwo = setTimeout(function() {
console.log("two!");
}, Math.random() * 1000);

inOrder(logOne, logTwo);

//一个 //两个

//它应该始终按顺序记录这两个,无论它们的时间如何

最佳答案

直接使用 setTimeout 是不可能的,因为您无法执行延迟等操作。但是您可以创建一个提供更多选项的包装器:

 function timer(cb, ms) {
let start = +new Date;
let timeout = setTimeout(cb, ms);

return {
ms,
stop() {
if(!timeout) return;
clearTimeout(timeout);
ms -= (start - new Date);
timeout = null;
},

start() {
if(ms > 0 && !timeout) {
start = +new Date;
timeout = setTimeout(cb, ms);
}
},
delay(time) {
this.stop();
ms += time;
this.start();
}
};
}

现在就很简单了:

 function inOrder(a, b) {
if(a.ms > b.ms)
b.delay(a.ms - b.ms);
}

可用作:

 const one = timer(() => console.log("one"), 1000);
const two = timer(() => console.log("two"), 500);

inOrder(one, two);

关于javascript - 如何编写一个函数 "inOrder"来接受两个回调并按顺序调用它们。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49516838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com