I have a while loop where I look for two attributes in the array, if they’re not there, then I invoke the sleep function for 10 seconds and look for those attributes again. I want there to be an Elapsed time there so that the user can see how long we’ve been looking for those attributes.
JavaScript
x
26
26
1
var flag1 = "false";
2
var flag2 = "false";
3
4
while (flag1 == "false" || flag2 == "false")
5
for { //for loop where it looks for some attributes in an array and if found, changes the respective flag to true
6
}
7
8
//if conditions so if the flags are still false then prints not found and tells that it will check again
9
if (flag1 == "false") {
10
print ("Attribute 1 not found. Check again in 10 seconds");
11
}
12
if (flag2 == "false") {
13
print ("Attribute 2 not found. Check again in 10 seconds");
14
}
15
16
//Stopwatch
17
var startTime = new Date();
18
sleep (10000);
19
var endTime = new Date();
20
var timeDiff = endTime - startTime;
21
timeDiff /= 1000;
22
var seconds = Math.round(timeDiff % 60);
23
print("Elapsed Time is " + seconds + "seconds");
24
}
25
print("Both attributes found."};
26
Expected output:
JavaScript
1
17
17
1
Attribute 1 not found Check again in 10 seconds.
2
Attribute 2 not found. Check again in 10 seconds.
3
Elapsed time: 0 seconds.
4
5
//after 10 seconds.
6
Attribute 1 not found Check again in 10 seconds.
7
Attribute 2 not found. Check again in 10 seconds.
8
Elapsed time: 10 seconds.
9
10
//after another 10 seconds.
11
Attribute 1 not found Check again in 10 seconds.
12
Attribute 2 not found. Check again in 10 seconds.
13
Elapsed time: 20 seconds.
14
15
//after another 10 seconds and assuming that the attribute was found in array this time.
16
Both attributes found.
17
Current Ouptut
JavaScript
1
7
1
Attribute 1 not found. Check again in 10 seconds.
2
Attribute 2 not found. Check again in 10 seconds.
3
Elapsed Time is 10seconds
4
Attribute 1 not found. Check again in 10 seconds.
5
Attribute 2 not found. Check again in 10 seconds.
6
Elapsed Time is 10seconds
7
The Elapsed time when printed always shows 10 seconds, I want it to keep incrementing. How would I do that?
Advertisement
Answer
Just move startTime
declaration
var startTime = new Date();
before the while loop:
JavaScript
1
21
21
1
var startTime = new Date();
2
3
while (flag1 == "false" || flag2 == "false")
4
.
5
6
7
if (flag1 && flag2) {
8
// if your condition is matched, exit the loop
9
break;
10
}
11
//Stopwatch
12
sleep (10000);
13
var endTime = new Date();
14
var timeDiff = endTime - startTime;
15
timeDiff /= 1000;
16
var seconds = Math.round(timeDiff % 60);
17
print("Elapsed Time is " + seconds + "seconds");
18
}
19
print("Both attributes found."};
20
21