Enter Your Email Address to Watch This Lesson

Your link to unlock this lesson will be sent to this email address.

Unlock this lesson and all 971 of the free egghead.io lessons, plus get JavaScript content delivered directly to your inbox!



Existing egghead members will not see this. Sign in.

Use JavaScript (ES6) generators to pause function execution

1:47 JavaScript lesson by

ES6 generators make it possible to pause and resume function execution at arbitrary points. This video will introduce you to the basics of generators with the yield keyword.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

ES6 generators make it possible to pause and resume function execution at arbitrary points. This video will introduce you to the basics of generators with the yield keyword.

Avatar
michalmw

What is name the font which you use?

In reply to egghead.io
Avatar
Alex

I think it's Operator Mono. Fair warning though, it's a very expensive font.

In reply to michalmw

In JavaScript, functions execute until they've reached a return keyword or the end of the function. If we execute our logger here and run it with Node, you will see that it first logs start, and it then logs end. EA6 generators are different. They can be paused and resumed at arbitrary points within the function.

To create a generator, we put an asterisk after the function keyword. If we execute this file again, you will see that nothing happens. Nothing is console.logged out. That is because when we call a generator, it returns an instance of itself but doesn't execute it.

To be more exact, we should call our generator create logger, and assign it to a variable called logger. To execute our generator, we call logger.next, which executes until the next block is over. If we run this, you'll see again that we logged start and we logged end.

To pause a generator, we use the yield keyword. The yield keyword tells the generator to stop executing at this point. If we run our file again, you will see this logs out start. The generator never reaches the console.log end. To execute the next block as well, we call logger.next again. As you can see, both start and end were logged out.

We can have as many of these yield keywords in our generator as we want. If we say console.log second block and third block here, and then call logger.next a bunch of times, if we execute this, you will see that everything executes as you expect.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?