Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function aborts after await

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading