繁体   English   中英

如何为数组 JavaScript 中的正确元素索引设置间隔倒计时?

[英]How to setInterval countdown for correct element index in the array JavaScript?

我遇到的问题是在我的componentDidUpdate()中,每次组件更新时, setInterval都会为每个具有patient.locationInfopatient.status值的患者倒计时。 我只需要在patient.locationInfopatient.status中具有值的数组中倒计时正确的患者索引,并且当用户单击Patient location column Buttons 并且Patient Obs detail column中包含文本/字符串时,它们具有设置的值。

componentDidUpdate() {

 this.state.patientInfo.forEach((patient, i) => {

           let seconds = 0;
           if (patient.locationInfo.length !== 0 && patient.status.length !== 0) {
               const checkoutMinPassed = setInterval(() => {
                   seconds++;

                   if (seconds === 5) {
                       clearInterval(checkoutMinPassed);
                       alert(patient.name + ' reached a min');
                   }
               }, 1000);
           }
       });


   }
PatientInfo Array

patientInfo = [
           { room: "1", name: 'John Nero', locationInfo: '', status: ''},
           { room: "2", name: 'Shawn Mic',  locationInfo: '', status: ''},
           { room: "3", name: 'Gereth Ma',  locationInfo: '', status: ''},
           { room: "4", name: 'Elminster',  locationInfo: '', status: ''},
           { room: "5", name: 'Rincewind',  locationInfo: '', status: ''},

表 UI 表示 1st、2nd、3rd 是否已经具有值 locationInfo 和 status。 当用户输入第 4 个患者时,setInterval 将为每个患者倒计时。 我只需要第 4 个病人的倒计时,因为前 3 个已经有了值。

为计时器 ID 使用全局变量。

    let checkoutMinPassed; 
    // at the top and outside of your component.

    // then inside your component,
              checkoutMinPassed = setTimeout(()=> { 
                   if (seconds === 5) {
                   clearInterval(checkoutMinPassed);;
                   }
                       }, 1000)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM