I wrote a generic waitFor function that would take the callback and a wait time and wait for it. From my understanding and observation, my code would wait for the whole time and then report status. I want to clear the timeout once the resolve is hit. How do I do that?
var _timer;
function waitForGeneric(method, max) {
var start = Date.now();
return new Promise((resolve, reject) => {
method();
function check() {
result = _connected;
if (result) {
console.log('connected to server[connection status]: ' + result);
window.clearTimeout(_timer);
resolve();
}
else {
if (Date.now() - start > max) {
console.log('waited for 30 seconds for connection[connection status]: ' + result);
reject();
}
else {
timer = window.setTimeout(check, 1000);
}
}
}
check();
});
}
Is this correct?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
I won't be able to respond further to this until tomorrow, and I don't necessarily have the tools to test what you are trying to do to make sure this is what you are going for... but if you want to run a function after a promise is resolved, you can attach the .then() method to the promise instance. Also, I could be wrong for your specific case, but I typically don't see window.clearTimeout or window.setTimeout, but rather they just have their respective function calls as clearTimeout and setTimeout.
var _timer;
function waitForGeneric(method, max)
{
var start = Date.now();
return new Promise((resolve, reject) => {
method();
function check() {
result = _connected;
if (result) {
console.log('connected to server[connection status]: ' + result);
clearTimeout(_timer);
resolve();
}
else {
if (Date.now() - start > max) {
console.log('waited for 30 seconds for connection[connection status]: ' + result);
reject();
}
else {
timer = setTimeout(check, 1000);
}
}
}
check();
}).then(function() {
clearTimeout(_timer);
});
}