Build a Recipe Step Timer in Vanilla JavaScript
Timers look simple until you build one. Use setInterval to count down from 60, and you will find that it drifts, pauses in background tabs and gets messy when you chain several steps. In this tutorial we will build a re
Timers look simple until you build one. Use setInterval to count down from 60, and you will find that it drifts, pauses in background tabs and gets messy when you chain several steps.
In this tutorial we will build a recipe step timer: a list of timed cooking steps that run one after another, with a clean countdown. It is a small project, but it teaches a real lesson about timing in the browser.
For example data, we will use a traditional South Indian rasam recipe, which has a few clear timed stages. You do not need to cook anything to follow along.
No framework, no build step. Just HTML and plain JavaScript.
What We Are Building
A page with a list of steps and a Start button. When you press Start, the timer runs the first step, shows the remaining time, then moves to the next step automatically and shows a message when everything is done.
The Sample Data
A rasam has stages with fixed cooking times, such as boiling the tamarind base, simmering the spices, and covering the pot after the tadka. The step-by-step method in this traditional South Indian rasam recipe gives the cooking ranges. We will use rounded values as example data:
js
const steps = [
{ label: "Boil tamarind, tomato, turmeric and salt", minutes: 7 },
{ label: "Simmer with the rasam masala", minutes: 5 },
{ label: "Cover the pot after the tadka", minutes: 1 },
];
These are only demo numbers. The dal water step and the froth signal are not timed here, because they depend on watching the pot.
Step 1: The HTML
html
<!DOCTYPE html>
Recipe Step Timer
<ol id="step-list"></ol>
<p id="current-label" aria-live="polite"></p>
<p id="countdown" aria-live="off">00:00</p>
<button id="start">Start</button>
<button id="reset" disabled>Reset</button>
Step 2: Pure Helper Functions
We keep the maths in small, pure functions that do not touch the page.
js
function formatTime(totalSeconds) {
const s = Math.max(0, Math.ceil(totalSeconds));
const minutes = Math.floor(s / 60);
const seconds = s % 60;
return ${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")};
}
function getRemainingSeconds(deadlineMs, nowMs) {
return Math.max(0, (deadlineMs - nowMs) / 1000);
}
function totalMinutes(list) {
return list.reduce((sum, step) => sum + step.minutes, 0);
}
Why Not Count Down by Subtracting 1?
A common beginner approach looks like this:
js
let seconds = 60;
setInterval(() => { seconds -= 1; }, 1000);
The problem is that setInterval is not exact. Browsers can delay it, especially in background tabs, so after a few minutes your timer is wrong.
A safer approach is to store a deadline and recalculate the remaining time on every tick:
js
const deadline = Date.now() + minutes * 60 * 1000;
// on each tick:
const remaining = getRemainingSeconds(deadline, Date.now());
The tick only decides when to redraw. The truth always comes from the clock, so the timer stays correct even if a tick runs late.
Step 3: Wire Up the Page
js
const listEl = document.getElementById("step-list");
const labelEl = document.getElementById("current-label");
const countdownEl = document.getElementById("countdown");
const startBtn = document.getElementById("start");
const resetBtn = document.getElementById("reset");
let timerId = null;
function renderSteps(activeIndex = -1) {
listEl.innerHTML = "";
steps.forEach((step, i) => {
const li = document.createElement("li");
li.textContent = ${step.label} (${step.minutes} min);
if (i === activeIndex) li.style.fontWeight = "bold";
listEl.appendChild(li);
});
}
function runStep(index) {
if (index >= steps.length) {
labelEl.textContent = "All steps done.";
countdownEl.textContent = "00:00";
startBtn.disabled = false;
timerId = null;
return;
}
const step = steps[index];
const deadline = Date.now() + step.minutes * 60 * 1000;
renderSteps(index);
labelEl.textContent = Step ${index + 1} of ${steps.length}: ${step.label};
timerId = setInterval(() => {
const remaining = getRemainingSeconds(deadline, Date.now());
countdownEl.textContent = formatTime(remaining);
if (remaining <= 0) {
clearInterval(timerId);
runStep(index + 1);
}
}, 250);
}
startBtn.addEventListener("click", () => {
startBtn.disabled = true;
resetBtn.disabled = false;
runStep(0);
});
resetBtn.addEventListener("click", () => {
clearInterval(timerId);
timerId = null;
startBtn.disabled = false;
resetBtn.disabled = true;
labelEl.textContent = "";
countdownEl.textContent = "00:00";
renderSteps();
});
renderSteps();
We tick every 250 ms. That is cheap, and it keeps the display from lagging by more than a fraction of a second. We use textContent throughout, so no raw HTML ever gets injected.
Step 4: Test the Helpers
Because the helpers are pure, you can test them without a browser clock:
js
console.log(formatTime(0)); // "00:00"
console.log(formatTime(65)); // "01:05"
console.log(formatTime(419.2)); // "07:00" (rounds up)
console.log(formatTime(-5)); // "00:00"
console.log(getRemainingSeconds(10000, 4000)); // 6
console.log(getRemainingSeconds(10000, 12000)); // 0
console.log(totalMinutes(steps)); // 13
The expected values above come from running this exact code. Rounding up with Math.ceil means the display shows 00:01 until the very last moment, instead of showing 00:00 while a fraction of a second remains.
Step 5: Make It Better
A sound or notification when a step ends. Ask for notification permission before you use it.
Pause and resume. Store the remaining time when pausing, and compute a new deadline when resuming.
Editable steps. Let the user add steps and durations with a small form.
Persist the recipe in localStorage, and wrap JSON.parse in try/catch.
Untimed steps. Add a step type with a βNextβ button for stages like βswitch off when it frothsβ.
Common Mistakes
Decrementing a counter in setInterval instead of using a deadline.
Forgetting to call clearInterval before starting the next step, which stacks timers.
Calling runStep(index + 1) before clearing the old interval.
Using innerHTML with user-provided text.
Treating a timer as the only signal. Real cooking also needs your eyes and nose.
A Note on Real Kitchens
A timer helps, but ingredients still matter. If you are cooking rasam for the first time, a ready rasam powder, one of the Indian spice blends made for a single dish, is a handy shortcut. For a faster, weeknight version of the same dish, see this easy South Indian rasam recipe.
If you plan to buy Indian spices or shop for Indian spices online, look for a full ingredients list, packed-on and best-before dates, and clear seller details. These checks tell you more about authentic Indian spices than any slogan. When you order Indian spices, small packs are easier to finish while they are fresh, and the best Indian spices for a dish like rasam are simply the ones that still smell fragrant when you open them.
FAQ
Why use a deadline instead of counting down?
setInterval can run late, especially in background tabs. A deadline based on Date.now() keeps the display correct no matter how late a tick runs.
Why 250 ms for the interval?
It is frequent enough to feel smooth, and cheap enough not to matter. You can use 1000 ms if you prefer, but the display may lag slightly.
Will it keep running in a background tab?
Browsers may throttle timers in background tabs, but because we use a deadline, the time shown is still correct when the tab comes back.
Can I use it for other recipes?
Yes. Change the steps array, and the rest of the code works as it is.
Should I use a library?
For this size of project, plain JavaScript is simpler and teaches you how timers really behave.
Wrapping Up
In about 70 lines, we built a recipe step timer with drift-safe timing, chained steps and testable helper functions. It is a small project, but it covers Date.now(), setInterval, clearInterval, DOM updates and pure functions.
If you build it, tell me which feature you would add first.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.