猿问

如何清除放置在 .map 回调函数中的间隔

我在数组上使用 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);

       })

);


绝地无双
浏览 141回答 2
2回答

慕斯王

该函数将清除所有间隔,但您也可以使用 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

Helenr

您需要先返回这些间隔才能清除所有这些间隔:const intervals = this.state.tokens   .map((token, index) => setInterval(() => {      ...   }, 1000)));intervals.forEach(interval => clearInterval(interval));实际上,我Promise在您的代码中看不到任何内容,您确定需要使用await Promise.all(...)吗?
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答