I figured it out ...

The function that called the function with the loop ends before the loop finishes, and that's why it gets stuck.

I'm pretty sure I encountered this before, and did not realize it until I found the cause.