How can I break from a while loop after 20 seconds have passed? I want to avoid the use of threads.
while (var) {
// ...do something
if (20secondsIsPassed) {
break;
}
}
How can I break from a while loop after 20 seconds have passed? I want to avoid the use of threads.
while (var) {
// ...do something
if (20secondsIsPassed) {
break;
}
}
If you have if
inside your while
loop, that checks for time elapsed, then you won't have exactly 20 seconds, but at least 20s. The easiest way though is something like this:
LocalDateTime then = LocalDateTime.now();
while (true) {
// logic
if (ChronoUnit.SECONDS.between(then, LocalDateTime.now()) >= 20) break;
}
Simply by knowing that each second represent 1000 millisecond you can do the following calculation:
long seconds = System.currentTimeMillis();
while (var && (seconds + (20 * 1000) > System.currentTimeMillis())) {
// ...do something
}