Promises are still asynchronous in this case. The loop in the while(true)
will keep executing and no other code will run in the meanwhile.
You simply can not have while(condition) { /* block that does not change 'condition' /* }
in plain old browser JavaScript. The code that changes isPaused in your case will never get the chance to execute. (well, you can with ES6 generators that let you explicitly yield control, but that's OT here).
You need to recurse chain the promises instead.
promise = promise.then(function pollUntil(){
return Q.delay(300).then(function(){
// recursively chain the continuation here this will check every 300 ms
// rather than freeze the code.
return isPaused ? pollUntil() : true;
});
});
This reads as: Continue the current action with pollUntil, which delays for 300 miliseconds, and then repeats (calls itself) until isPaused is no longer true.
Note, you can not add .then
to the external promise, since you (or might need to in the more general case) chain to it later.
Of course it would be preferable to create a pause()
promise that will resolve when you're no longer paused.