Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Build a Simple Dynamic Site with Node.js Creating a Simple Server in Node.js Creating a Simple Server

Gabriel C. Cavallo
Gabriel C. Cavallo
4,438 Points

how 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
Emmanuel C
10,635 Points

Hey 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
Gabriel C. Cavallo
4,438 Points

Many thanks! I guess I have to go deeper into the asynch aspects of JS