In a browser extension I’m trying to:
- find a button
- update its text every second for 10 seconds
- invoke submit
Simple enough, but unfortunately I’m a JavaScript novice.
I’m clueless: Why does the code below not reach line #15 (after await)?
const Timeout = 10000;
const CountdownStep = 1000;
async function scheduleSubmit(node, timeout) {
originalTextContent = node.textContent;
while (timeout > 0) {
console.log(`Timeout: ${timeout}`);
try {
await new Promise((resolve => setTimeout(() => {
console.log(`[Promise] Timeout: ${timeout}`);
node.textContent = `${originalTextContent} (${timeout / 1000})`;
timeout -= CountdownStep;
console.log(`[Promise] Timeout: ${timeout}`);
}, CountdownStep)));
console.log('Hello? Helloooooooo??');
} catch (err) {
log(`Error: ${err}`);
}
}
node.submit();
}
scheduleSubmit(document.getElementById('foo'), Timeout);
<html><body>
<button type="button" id="foo">Run</button>
</body></html>
>Solution :
If you extract a simple delay helper that returns a Promise that resolves after the specified amount of time you code becomes way more readable. Not to speak you can test and debug your code separately to identify the issue.
const Timeout = 10000;
const CountdownStep = 1000;
function delay(timeout) {
return new Promise(resolve => setTimeout(resolve, timeout))
}
async function scheduleSubmit(node, timeout) {
originalTextContent = node.textContent;
while (timeout > 0) {
try {
await delay(CountdownStep);
node.textContent = `${originalTextContent} (${timeout / 1000})`;
timeout -= CountdownStep;
} catch (err) {
log(`Error: ${err}`);
}
}
node.submit();
}
scheduleSubmit(document.getElementById('foo'), Timeout);
<html><body>
<button type="button" id="foo">Run</button>
</body></html>