while loop executes AFTER break statement

255 views
Skip to first unread message

Michael Covell

unread,
Oct 27, 2023, 2:51:02 AM10/27/23
to Google Apps Script Community
How is "hello world" printed twice?  Isn't this impossible?


function IMPOSSIBLE_LOOP() {
  while (true) {
    Logger.log('hello world')
    break
  }
  Utilities.sleep(2000)
  return 'done'
}
Logger.log(IMPOSSIBLE_LOOP())
Execution log
3:03:52 PM
Notice
Execution started
3:03:52 PM
Info
hello world
3:03:54 PM
Info
done
3:03:54 PM
Info
hello world
3:03:57 PM
Notice
Execution completed

Jim Willeke

unread,
Oct 27, 2023, 7:30:02 AM10/27/23
to Google Apps Script Community
You are calling function IMPOSSIBLE_LOOP() twice.

The order of execution is not what some would expect.

I assume this is being run from the code console and directly executing the function  IMPOSSIBLE_LOOP().

This might help explain the order of execution.
In the code console run starthere()

function starthere(){
Logger.log(IMPOSSIBLE_LOOP())
}

function IMPOSSIBLE_LOOP() {
while (true) {
Logger.log('hello world')
break
}
Utilities.sleep(2000)
return 'return from IMPOSSIBLE_LOOP'
}


Logger.log(`finished running`);


Reply all
Reply to author
Forward
0 new messages