Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

setTimeout() and setInterval() in Node.js

JavaScript provides timer functions to execute code after a delay or repeatedly at a specified interval. The two commonly used timer functions are setTimeout() and setInterval().


1. Introduction to Timer Functions

Imagine Samadhan is studying Node.js at CIIT Training Institute. He wants to display a reminder after three seconds. Pradnya wants to display a message repeatedly every two seconds. JavaScript timer functions can handle both requirements.

Simple Trick: setTimeout() means execute once after a delay. setInterval() means execute repeatedly at an interval.

2. What is setTimeout()?

The setTimeout() function schedules a callback to run after a specified delay in milliseconds. It does not guarantee execution at the exact requested time.

Syntax
JavaScript
setTimeout(callback, delayInMilliseconds);
Parameter Description
callback The function to execute after the delay.
delayInMilliseconds The minimum delay before the callback becomes eligible to run.

3. Example of setTimeout()

Samadhan wants to display a welcome message after three seconds.

JavaScript
console.log("Samadhan started learning Node.js.");

setTimeout(() => {
    console.log("Welcome to CIIT Training Institute!");
}, 3000);

console.log("Samadhan is practicing JavaScript.");
Output
Samadhan started learning Node.js.
Samadhan is practicing JavaScript.
Welcome to CIIT Training Institute!
The last message becomes eligible to execute after approximately three seconds.
Explanation
  1. The first console.log() displays the starting message.
  2. setTimeout() schedules its callback for approximately three seconds later.
  3. JavaScript continues executing the next statement without waiting for the timer.
  4. After the delay, the callback runs when the event loop can process it.

4. setTimeout() Execution Flow

setTimeout() Flow Diagram
Start Program
↓
Schedule setTimeout()
Register the callback with a delay.
↓
Execute Remaining Code
The program continues without waiting for the timer.
↓
Timer Delay Expires
The callback becomes eligible to run.
↓
Execute Callback
When the event loop can process it.

5. What is setInterval()?

The setInterval() function repeatedly schedules a callback at a specified interval until the interval is cancelled or the program stops.

Syntax
JavaScript
setInterval(callback, intervalInMilliseconds);

For example, an interval of 2000 milliseconds requests repeated execution approximately every two seconds.

6. Example of setInterval()

Pradnya wants to display a practice reminder every two seconds. We can use setInterval() for this task.

JavaScript
let count = 1;

const timer = setInterval(() => {
    console.log("Pradnya is practicing Node.js: " + count);

    count++;

    if (count > 3) {
        clearInterval(timer);
        console.log("Practice reminder completed.");
    }
}, 2000);
Output
Pradnya is practicing Node.js: 1
Pradnya is practicing Node.js: 2
Pradnya is practicing Node.js: 3
Practice reminder completed.
Each reminder is requested approximately two seconds apart.
Explanation
  1. count starts at 1.
  2. setInterval() schedules the callback repeatedly.
  3. Each execution displays the current count and increments it.
  4. When the count becomes greater than 3, clearInterval(timer) stops future interval callbacks.
  5. The completion message is displayed after the third reminder.

7. setInterval() Execution Flow

setInterval() Flow Diagram
Start Program
↓
Start Interval Timer
Schedule repeated callback execution.
↓
Execute Callback
Display a message or perform a task.
↓
Repeat at the Interval
Continue while the interval remains active.
↓
clearInterval()
Cancel future interval callbacks.

8. Using clearTimeout()

The clearTimeout() function cancels a scheduled timeout callback if it has not already started executing.

JavaScript
const timer = setTimeout(() => {
    console.log("This message will not appear.");
}, 3000);

clearTimeout(timer);

console.log("Timeout cancelled.");
Output
Timeout cancelled.

The timeout is cancelled before its callback runs, so the scheduled message is not displayed.

9. Using clearInterval()

The clearInterval() function cancels future executions of an interval timer.

JavaScript
let count = 0;

const timer = setInterval(() => {
    count++;
    console.log("Count: " + count);

    if (count === 3) {
        clearInterval(timer);
        console.log("Interval stopped.");
    }
}, 1000);
Output
Count: 1
Count: 2
Count: 3
Interval stopped.

10. Difference between setTimeout() and setInterval()

setTimeout() setInterval()
Schedules a callback to run once after a delay. Schedules a callback to run repeatedly.
Uses a delay in milliseconds. Uses an interval in milliseconds.
Cancelled using clearTimeout(). Cancelled using clearInterval().
Useful for delayed messages and one-time actions. Useful for repeated reminders and periodic tasks.
Normally invokes its callback once. Continues until cancelled or the runtime stops.

11. Real-World Example: Course Reminder

At CIIT Training Institute, Samadhan wants to show a welcome message after a delay, while Pradnya wants to display a limited number of reminders.

JavaScript
// One-time welcome message
setTimeout(() => {
    console.log("Welcome, Samadhan!");
}, 1000);

// Repeated reminders
let reminderCount = 0;

const reminderTimer = setInterval(() => {
    reminderCount++;

    console.log("Pradnya: Remember to practice JavaScript.");

    if (reminderCount === 2) {
        clearInterval(reminderTimer);
        console.log("Pradnya's reminders are complete.");
    }
}, 2000);
Expected Output
Welcome, Samadhan!
Pradnya: Remember to practice JavaScript.
Pradnya: Remember to practice JavaScript.
Pradnya's reminders are complete.
The welcome message is scheduled after one second. The reminders are scheduled approximately two seconds apart.
Note: The exact timing depends on the runtime and event loop. In this example, the welcome message is scheduled before the first reminder, so it is expected to appear first.

12. Common Mistakes

Mistake Correct Approach
Assuming a timer executes at the exact requested time. Remember that the delay is a minimum waiting period, not an exact execution guarantee.
Forgetting to stop a repeating interval. Use clearInterval() when repetition is no longer required.
Calling clearTimeout() after the callback has already run. Cancel the timeout before its callback begins if cancellation is needed.
Using setInterval() for every repeated asynchronous task. Consider recursive setTimeout() when each task must finish before the next one is scheduled.

13. Important Points to Remember

  • setTimeout() schedules a callback after a delay.
  • setInterval() schedules repeated callback execution.
  • Timer delays are measured in milliseconds.
  • clearTimeout() cancels a pending timeout.
  • clearInterval() stops future interval callbacks.
  • Timer callbacks run when the event loop can process them.
  • Timers do not block the entire JavaScript program while waiting.

Summary

In this lesson, we learned how setTimeout() schedules a callback after a delay and how setInterval() schedules repeated callbacks. We also learned to cancel timers using clearTimeout() and clearInterval(), understand timer execution flow, and apply timer functions to practical examples involving Samadhan, Pradnya, and CIIT Training Institute.