π°οΈ Node.js Timers & Console: Your Kitchen Timer & Notepad
The Big Picture: What Are We Learning?
Imagine youβre in a kitchen. You have two super helpful tools:
- A Kitchen Timer β²οΈ β It helps you do things later or again and again
- A Notepad π β You write down whatβs happening so you donβt forget
In Node.js:
- Timers = Your kitchen timer (do stuff after waiting)
- Console = Your notepad (write messages to see whatβs happening)
Letβs explore both!
π³ PART 1: TIMERS β Doing Things Later
What Are Timers? (Overview)
Think about baking cookies. You put them in the oven and set a timer for 10 minutes. You donβt stand there staring β you go do other things! When the timer rings, you take them out.
Node.js timers work the same way:
- Tell Node.js to wait
- Then do something when time is up
- Meanwhile, Node.js can do other work!
// I'll say "Ding!" after 3 seconds
setTimeout(() => {
console.log("Ding! Cookies ready!");
}, 3000);
console.log("Timer set, doing other stuff...");
What prints first? βTimer set, doing other stuffβ¦β β because Node.js doesnβt wait around!
β° Setting Timers
Node.js gives you THREE types of timers:
1. setTimeout β βDo this ONCE after waitingβ
Like setting an alarm that rings just once.
// Ring after 2 seconds (2000 milliseconds)
setTimeout(() => {
console.log("Wake up!");
}, 2000);
Real-life example: A reminder to drink water in 1 hour.
2. setInterval β βDo this AGAIN and AGAINβ
Like a heartbeat β it keeps going at regular intervals.
// Tick every 1 second
setInterval(() => {
console.log("Tick...");
}, 1000);
Real-life example: A clock that ticks every second.
3. setImmediate β βDo this RIGHT AFTER current workβ
Like saying βIβll do this next, but let me finish what Iβm doing first.β
setImmediate(() => {
console.log("Done immediately after!");
});
console.log("This prints first");
Output:
This prints first
Done immediately after!
π Clearing Timers
What if you set a timer but change your mind? Cancel it!
Each set function returns an ID. Use that ID to cancel:
| Set Function | Clear Function |
|---|---|
setTimeout |
clearTimeout |
setInterval |
clearInterval |
setImmediate |
clearImmediate |
// Set a timer
const timerId = setTimeout(() => {
console.log("This won't print!");
}, 5000);
// Cancel it before it fires
clearTimeout(timerId);
console.log("Timer cancelled!");
Story Time: π You ordered pizza (setTimeout). But then you found food at home. You cancel the order (clearTimeout). No pizza arrives!
Stopping a Repeating Timer
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 3) {
clearInterval(intervalId);
console.log("Stopped counting!");
}
}, 1000);
Output:
Count: 1
Count: 2
Count: 3
Stopped counting!
π Timer Promises API
The Modern Way! π
Old timers use callbacks. New timers can use async/await β much cleaner!
First, import from timers/promises:
import { setTimeout } from 'timers/promises';
async function cookDinner() {
console.log("Cooking...");
// Wait 2 seconds (no callback needed!)
await setTimeout(2000);
console.log("Dinner is ready!");
}
cookDinner();
Why is this better?
- No callback pyramids ποΈ
- Code reads top-to-bottom
- Easier to understand!
All Timer Promises
import {
setTimeout,
setInterval,
setImmediate
} from 'timers/promises';
// setTimeout with value
const result = await setTimeout(1000, 'Hello!');
console.log(result); // 'Hello!'
// setImmediate
await setImmediate();
console.log('Ran immediately after!');
π PART 2: CONSOLE β Your Notepad
What Is Console? (Overview)
The console is like a notepad where you write messages. It helps you:
- See what your code is doing
- Find bugs (detective work! π)
- Show information to developers
Every program needs a way to βtalkβ β console is how Node.js talks to you!
π¨οΈ Console Output
The console has different βpensβ for different messages:
console.log β Regular Messages
console.log("Hello, World!");
console.log("The answer is", 42);
console.log("User:", { name: "Alex", age: 10 });
console.error β Something Went Wrong! π¨
console.error("Oops! Something broke!");
Shows in red in most terminals.
console.warn β Be Careful! β οΈ
console.warn("This might cause problems...");
Shows in yellow in most terminals.
console.info β FYI π‘
console.info("Server started on port 3000");
Same as log, but shows youβre giving information.
console.debug β For Detectives π
console.debug("Checking value:", someVariable);
Extra details for debugging.
π console.table β Pretty Tables!
When you have a list of things, console.table makes it beautiful:
const pets = [
{ name: "Max", type: "Dog", age: 3 },
{ name: "Whiskers", type: "Cat", age: 5 },
{ name: "Goldie", type: "Fish", age: 1 }
];
console.table(pets);
Output:
βββββββββββ¬ββββββββββββ¬βββββββββ¬ββββββ
β (index) β name β type β age β
βββββββββββΌββββββββββββΌβββββββββΌββββββ€
β 0 β 'Max' β 'Dog' β 3 β
β 1 β 'Whiskers'β 'Cat' β 5 β
β 2 β 'Goldie' β 'Fish' β 1 β
βββββββββββ΄ββββββββββββ΄βββββββββ΄ββββββ
So much easier to read! π
You can also pick specific columns:
console.table(pets, ['name', 'type']);
β±οΈ Console Timing β How Fast Is Your Code?
Want to know how long something takes? Use timing!
console.time & console.timeEnd
console.time('cooking');
// Simulate cooking (do some work)
for (let i = 0; i < 1000000; i++) {
// cooking...
}
console.timeEnd('cooking');
Output:
cooking: 5.234ms
The label must match! Both use 'cooking'.
console.timeLog β Check Time Without Stopping
console.time('baking');
// Step 1
console.timeLog('baking', 'Mixed ingredients');
// Step 2
console.timeLog('baking', 'Put in oven');
// Done
console.timeEnd('baking');
Output:
baking: 1.2ms Mixed ingredients
baking: 2.5ms Put in oven
baking: 3.8ms
π― Quick Summary
graph LR A["Node.js Core Utilities"] --> B["β° Timers"] A --> C["π Console"] B --> D["setTimeout - Once"] B --> E["setInterval - Repeat"] B --> F["setImmediate - Next"] B --> G["clear* - Cancel"] B --> H["Promises API - Modern"] C --> I["log/error/warn"] C --> J["table - Pretty Data"] C --> K["time/timeEnd - Speed"]
π You Did It!
You now know how to:
- β° Make code wait with
setTimeout - π Repeat actions with
setInterval - π Cancel timers when you change your mind
- β¨ Use modern promises for cleaner code
- π Print messages with
console.log - π Make pretty tables with
console.table - β±οΈ Measure how fast your code runs
Youβre now a Timer & Console expert! π
Remember: Timers are your kitchen timer, Console is your notepad. Use them together to cook amazing Node.js programs! π³π
