我在数组上使用map方法,以便设置给定次数向API发送请求的时间间隔(每个timeInterval具有不同的访问令牌)。
我可以以某种方式创建一个可以从外部清除这些间隔的函数吗?
await Promise.all(
this.state.tokens
.map((token, index) => {
const driver = setInterval(() => {
if (decodedPolylines[index].length > 1) {
api.sendLocation(
token,
decodedPolylines[index][0][0].toString(),
decodedPolylines[index][0][1].toString()
);
} else {
api.clockInOut(
token,
'out',
decodedPolylines[index][0][0].toString(),
decodedPolylines[index][0][1].toString()
);
clearInterval(driver);
}
}, 1000);
})
);
最佳答案
该函数将清除所有间隔,但是如果只希望清除一些间隔,则也可以使用filter():
const drivers = [];
await Promise.all(
this.state.tokens
.map((token, index) => {
const driver = setInterval(() => {
if (decodedPolylines[index].length > 1) {
api.sendLocation(
token,
decodedPolylines[index][0][0].toString(),
decodedPolylines[index][0][1].toString()
);
} else {
api.clockInOut(
token,
'out',
decodedPolylines[index][0][0].toString(),
decodedPolylines[index][0][1].toString()
);
clearInterval(driver);
}
}, 1000);
drivers.push(driver);
})
);
const clearDrivers = () => {
drivers.forEach(d => clearInterval(d));
};
// call clearDrivers() when you want to stop all intervals
关于javascript - 如何清除.map回调函数中放置的间隔,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58289031/