Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGabriel C. Cavallo
4,438 Pointshow JS process the lines
in this video the tutor sets the setInterval function's callback to be executed with 1 second of delay. We can see however that the response.end function kicks in and the setInterval function does not run. If JS executes each line from top to down, should it wait for the setInterval function to finish running before the next line is executed?
2 Answers
Emmanuel C
10,636 PointsHey Gabriel,
One of the coolest features (in my opinion) about JS is that the program actually runs, what is called asynchronously. While the program does run line by line from top to bottom. The program doesn't stop to wait for any statement to finish before it moves on to the next line. When it gets to the setInterval function, it runs it, but since it has to wait an entire second till it can run that call back, it moves on to run the rest of the code while still waiting for that whole second to process. Since the next statement is response.end and it take less than that second to run, it does run and ends the response.
I hope that makes sense. Asynchronous programming can be really useful and a new course just came out for it. Asynchronous programming in JS
Gabriel C. Cavallo
4,438 PointsMany thanks! I guess I have to go deeper into the asynch aspects of JS