R
Rishtaara
JavaScript Fundamentals
Lesson 8 of 28Article18 min

Functions & Timers

A function is a reusable block of code with a name. Call it with parentheses and arguments.

Function Declaration

A function is a reusable block of code with a name. Call it with parentheses and arguments.

Real-life example: A function is a recipe card — write once, cook many times.

Function declaration
function greet(name) {
  return "Hello, " + name + "!";
}
console.log(greet("Asha")); // "Hello, Asha!"

Function Expression

Store a function in a variable. Often used when passing functions as values.

Real-life example: Same recipe card, but kept inside a folder labeled "myRecipe" instead of pinned on the wall.

Function expression
const add = function (a, b) {
  return a + b;
};
console.log(add(2, 3)); // 5

Arrow Functions

Short syntax: (params) => expression or => { statements }. Great for small callbacks.

Real-life example: A quick sticky note instead of a full recipe card — same job, less writing.

Arrow function
const double = (n) => n * 2;
const sum = (a, b) => {
  return a + b;
};
console.log(double(5)); // 10

Parameters, Return & Default Parameters

Parameters are inputs. return sends a value back. Default parameters fill in when an argument is missing.

Real-life example: A chai order — size defaults to "regular" if you say nothing.

Defaults and return
function makeChai(cups = 1, sugar = true) {
  return `${cups} cup(s), sugar: ${sugar}`;
}
console.log(makeChai());       // 1 cup(s), sugar: true
console.log(makeChai(2, false));

setTimeout and setInterval

setTimeout runs code once after a delay (milliseconds). setInterval repeats on a timer.

Real-life example: setTimeout — oven timer rings once. setInterval — a clock ticking every second.

Timers
// Run once after 2 seconds
const onceId = setTimeout(() => {
  console.log("2 seconds passed");
}, 2000);

// Run every 1 second
const repeatId = setInterval(() => {
  console.log("tick");
}, 1000);

clearTimeout and clearInterval

Save the timer id and pass it to clearTimeout or clearInterval to stop future runs.

Real-life example: Cancel the oven alarm before it rings if you already removed the cake.

Timers do not pause your whole page — JS keeps running other code. The browser calls your function when time is up.
Stopping timers
const id = setInterval(() => console.log("hi"), 500);
clearInterval(id); // stops the repeating timer
How timers fit the event loop