【发布时间】:2021-04-24 22:44:32
【问题描述】:
我有一个 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移到循环之外? -
@HereticMonkey 谢谢这确实有帮助,但如果在第一次迭代本身中找到这两个属性,它仍然会打印 Elapsed Time is .... 我该如何应对呢?如果在第一次迭代中找到这两个属性,我不希望它
sleep(1000)或打印elapsed time。 -
sleep (10000)是做什么的?也许看到Sleep in JavaScript - delay between actions。
标签: javascript datetime for-loop while-loop