首页 > 解决方案 > 如何在 while 循环中不断增加 Elapsed time 变量,而不是每次都从 0 秒开始

问题描述

我有一个 while 循环,在其中查找数组中的两个属性,如果它们不存在,那么我调用 sleep 函数 10 秒并再次查找这些属性。我希望那里有一个经过的时间,以便用户可以看到我们一直在寻找这些属性多长时间。

var flag1 = "false";
var flag2 = "false";

while (flag1 == "false" || flag2 == "false")
   for { //for loop where it looks for some attributes in an array and if found, changes the respective flag to true
   }

   //if conditions so if the flags are still false then prints not found and tells that it will check again
   if (flag1 == "false") {
       print ("Attribute 1 not found. Check again in 10 seconds");
   }
   if (flag2 == "false") {
       print ("Attribute 2 not found. Check again in 10 seconds");
   }
   
   //Stopwatch 
   var startTime = new Date();
   sleep (10000);
   var endTime = new Date();
   var timeDiff = endTime - startTime;
   timeDiff /= 1000;
   var seconds = Math.round(timeDiff % 60);
   print("Elapsed Time is " + seconds + "seconds");
}
print("Both attributes found."};

预期输出:

Attribute 1 not found Check again in 10 seconds.
Attribute 2 not found. Check again in 10 seconds.
Elapsed time: 0 seconds.

//after 10 seconds.
Attribute 1 not found Check again in 10 seconds.
Attribute 2 not found. Check again in 10 seconds.
Elapsed time: 10 seconds.

//after another 10 seconds.
Attribute 1 not found Check again in 10 seconds.
Attribute 2 not found. Check again in 10 seconds.
Elapsed time: 20 seconds.

//after another 10 seconds and assuming that the attribute was found in array this time.
Both attributes found.

当前输出

Attribute 1 not found. Check again in 10 seconds.
Attribute 2 not found. Check again in 10 seconds.
Elapsed Time is 10seconds
Attribute 1 not found. Check again in 10 seconds.
Attribute 2 not found. Check again in 10 seconds.
Elapsed Time is 10seconds

打印时经过的时间总是显示 10 秒,我希望它不断增加。我该怎么做?

标签: javascriptdatetimefor-loopwhile-loop

解决方案


只需移动startTime声明

var startTime = new Date();

在while循环之前:

var startTime = new Date();

while (flag1 == "false" || flag2 == "false")
   .... 


   if (flag1 && flag2) {
     // if your condition is matched, exit the loop
     break;
   }
   //Stopwatch 
   sleep (10000);
   var endTime = new Date();
   var timeDiff = endTime - startTime; 
   timeDiff /= 1000;
   var seconds = Math.round(timeDiff % 60);
   print("Elapsed Time is " + seconds + "seconds");
}
print("Both attributes found."};
   

推荐阅读