1

So, when i use a continue statement in a function inside a while loop, I get this error:

SyntaxError: Undefined label 'start'
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)

Here is my code:

var continuable = true;
start: while(true){
    console.log('Executed the code!');
    setTimeout(function(){
        if (continuable == true){
            continue start;
        }
    }, 250);
    break;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
jan Sena
  • 31
  • 1
  • 8
  • 3
    Your continue statement is *in another function*. By the time it executes, the current function that has the label has finished executing and the stack has been long cleared of it. How would a jump back even work? – VLAZ Mar 26 '20 at 07:30

1 Answers1

2

You can only break or continue a loop using break or continue if the loop is inside the function you're currently in. In this case, your continue start is referencing a loop which is outside of the current running function, so it's not permitted.

You can make it work by awaiting 250ms inside a loop instead:

const delay = ms => new Promise(res => setTimeout(res, ms));

(async () => {
  var continuable = true;
  setTimeout(() => { continuable = false; }, 1500);
  start: while(true){
    console.log('Executed the code!');
    await delay(250);
    if (continuable == true){
      console.log('continuing');
      continue start;
    }
    console.log('not continuing, executing body of loop');
  }
})();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Surprising we can await inside a while – mplungjan Mar 26 '20 at 07:38
  • 1
    @mplungjan I'm not sure it's very surprising. [You can do it in a `for..of`](https://stackoverflow.com/questions/24586110/resolve-promises-one-after-another-i-e-in-sequence), so I can't see a reason why it can't be in any loop constructs. Since `await` puts the function to sleep, there is no real inherent problem with this, when the Promise is resolved, the function context is restored and execution resumes anyway. – VLAZ Mar 26 '20 at 07:44
  • You can also do it in normal `for` loops, as well as (weird) bare blocks – CertainPerformance Mar 26 '20 at 07:45
  • I am just so used to the computer not getting any time to update inside such a loop – mplungjan Mar 26 '20 at 07:53