Timers and Console

Back

Loading concept...

πŸ•°οΈ 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:

  1. A Kitchen Timer ⏲️ β€” It helps you do things later or again and again
  2. 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! πŸ³πŸ“

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.