为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

绝地无双 2021-11-12 18:25:18
我在数组上使用 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);       }));
查看完整描述

2 回答

?
慕斯王

TA贡献1864条经验 获得超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


查看完整回答
反对 回复 2021-11-12
?
Helenr

TA贡献1780条经验 获得超4个赞

您需要先返回这些间隔才能清除所有这些间隔:


const intervals = this.state.tokens

   .map((token, index) => setInterval(() => {

      ...

   }, 1000))

);


intervals.forEach(interval => clearInterval(interval));

实际上,我Promise在您的代码中看不到任何内容,您确定需要使用await Promise.all(...)吗?


查看完整回答
反对 回复 2021-11-12
  • 2 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信