The Secret Life of JavaScript: The Generator
dev.to·3d·
Discuss: DEV
🚴Cycling
Preview
Report Post

How to pause, resume, and control the flow of execution.


Timothy was staring at a frozen screen. He forced a reload, but he looked defeated.

function createIds() {
let i = 0;
while (true) {
return i++; // This doesn't work like I want...
}
}
// He wanted a new ID every time he called it.
// Instead, he got "0" every time.


"I’m trying to create a system that generates unique IDs forever," Timothy explained. "But if I use a loop, it hangs the browser. If I don’t use a loop, the variable resets every time I call the function."

Margaret pulled up a chair. "You are running into the Run-to-Completion rule," she said.

"Normal functions are like a sprint," she continued. "Once they start, they cannot stop until they finish. You need a function that can…

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help