javascript - 如何在 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 秒,我希望它不断增加。我该怎么做?
解决方案
只需移动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."};
推荐阅读
- javascript - Font Awsome icons break my React.js logic
- javascript - why my react native component keep refreshing?
- image - Docker container exits as soon as I start it
- laravel - Laravel with form wizard validation using axios
- javascript - 谷歌表格中字符串内的美元符号+双花括号(某种变量?)
- java - 如何将 pojo id 的映射收集到 pojo 上集合的一组属性
- java - 如何检测JVM因错误异常退出?
- r - 忽略 readtext r 中的错误
- python - Tkinter - 在 Ubuntu 上设置按钮背景透明
- java - 安排休眠在特定时间保存,直到被告知才同步