I have a small JavaScript code in which I'm trying to use setTimeout
to either wait for some external input to arrive (via responseReceived
variable), OR wait for a max threshold time and then quit.
Here's the code:
var MAX_WAIT_THRESHOLD = 5000;
var keepWaiting = true;
var waitInterval = 500;
var totalTimeWaited = 0;
alert("Alert1");
while(keepWaiting == true) {
setTimeout(function() {
totalTimeWaited = totalTimeWaited + waitInterval;
alert("Alert2");
if(responseReceived == true || totalTimeWaited >= MAX_WAIT_THRESHOLD) {
keepWaiting = false;
}
}, waitInterval);
}
The problem is for some reason setTimeout(..)
never actually calls the anonymous function created inside it. I checked this by placing breakpoints in Chrome's JavaScript execution control, and execution never actually stops at any breakpoint placed inside the anonymous function. JavaScript's execution keeps toggling between the while ..
line and setTimout(..)
line. responseReceived
is set elsewhere in the code. Another way of saying this is that the first alert shows (Alert1) but the second one never shows (Alert2).
What am I doing wrong ?
EDIT:
I went through the 'duplicate' question reported but I fail to see how that is relevant to my question. My question is not regarding the while
loop. Rather it's about why the internal anonymous function isn't being called.