[英]How to clear interval placed inside .map callback function
I'm using map method on array in order to set intervals sending requests to API for a given number of times (each timeInterval have different access token).我在数组上使用 map 方法,以便设置在给定次数内向 API 发送请求的间隔(每个 timeInterval 具有不同的访问令牌)。 Can I somehow create a function that will clear those intervals from outside?
我可以以某种方式创建一个 function 来从外部清除这些间隔吗?
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);
})
);
The function will clear all intervals, but you can also use filter() in case you want only some to be cleared: function 将清除所有间隔,但如果您只想清除一些间隔,您也可以使用 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
You need to return those intervals first to be able to clear all of them:您需要先返回这些间隔才能清除所有这些间隔:
const intervals = this.state.tokens
.map((token, index) => setInterval(() => {
...
}, 1000))
);
intervals.forEach(interval => clearInterval(interval));
Actually, i can't see any Promise
in your code, are you sure you need to use await Promise.all(...)
?实际上,我在您的代码中看不到任何
Promise
,您确定需要使用await Promise.all(...)
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.