Build a Pomodoro Timer in Vanilla JavaScript (No Libraries, No Drift)

2026-12-01来源 dev.toEnglish

Most "build a timer" tutorials count down by subtracting one from a number every second. It works until you switch tabs. Browsers throttle background timers, so your 25 minutes can quietly stretch to 27.

In this tutorial we will build a small Pomodoro timer in plain JavaScript that stays accurate, switches between focus and break sessions, and plays a sound when time is up. No libraries and no build step.

What we are building

  • A 25-minute focus session, a 5-minute short break, and a 15-minute long break after every fourth session
  • Start/pause and reset buttons
  • The remaining time shown in the browser tab title, so you can see it from another tab
  • A short beep when a session ends

If you only want a ready-made version, there is a free Pomodoro timer you can use in the browser. If you want to understand how it works, keep reading.

Step 1: The HTML

Create index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Pomodoro Timer</title> <link rel="stylesheet" href="style.css" /> </head> <body> <main class="card"> <p id="label">Focus</p> <h1 id="display">25:00</h1> <div class="buttons"> <button id="toggle">Start</button> <button id="reset" class="secondary">Reset</button> </div> <p id="rounds">Completed focus sessions: 0</p> </main> <script src="app.js"></script> </body> </html> 

Step 2: The CSS

Create style.css. Nothing fancy, just enough to be readable:

body { margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: system-ui, sans-serif; background: #0f2e2b; } .card { background: #fff; padding: 2rem 3rem; border-radius: 16px; text-align: center; } #display { font-size: 4rem; margin: 0.5rem 0 1rem; font-variant-numeric: tabular-nums; } .buttons { display: flex; gap: 0.75rem; justify-content: center; } button { padding: 0.6rem 1.4rem; font-size: 1rem; border: 0; border-radius: 8px; background: #14b8a6; cursor: pointer; } button.secondary { background: #e5e7eb; } 

tabular-nums keeps every digit the same width, so the clock doesn't jitter as numbers change.

Step 3: The JavaScript

Create app.js:

const MODES = { work: { seconds: 25 * 60, label: "Focus" }, short: { seconds: 5 * 60, label: "Short break" }, long: { seconds: 15 * 60, label: "Long break" }, }; const display = document.getElementById("display"); const label = document.getElementById("label"); const toggleBtn = document.getElementById("toggle"); const resetBtn = document.getElementById("reset"); const roundsEl = document.getElementById("rounds"); let mode = "work"; let remaining = MODES.work.seconds; let endTime = null; let timerId = null; let rounds = 0; function format(total) { const m = String(Math.floor(total / 60)).padStart(2, "0"); const s = String(total % 60).padStart(2, "0"); return `${m}:${s}`; } function render() { display.textContent = format(remaining); label.textContent = MODES[mode].label; roundsEl.textContent = `Completed focus sessions: ${rounds}`; document.title = `${format(remaining)} - ${MODES[mode].label}`; } function beep() { try { const ctx = new AudioContext(); const osc = ctx.createOscillator(); osc.frequency.value = 880; osc.connect(ctx.destination); osc.start(); osc.stop(ctx.currentTime + 0.3); } catch { // Audio is optional, so ignore failures. } } function tick() { remaining = Math.max(0, Math.ceil((endTime - Date.now()) / 1000)); render(); if (remaining === 0) finish(); } function start() { if (timerId) return; endTime = Date.now() + remaining * 1000; timerId = setInterval(tick, 250); toggleBtn.textContent = "Pause"; } function pause() { clearInterval(timerId); timerId = null; toggleBtn.textContent = "Start"; } function finish() { pause(); beep(); if (mode === "work") { rounds += 1; mode = rounds % 4 === 0 ? "long" : "short"; } else { mode = "work"; } remaining = MODES[mode].seconds; render(); } function reset() { pause(); mode = "work"; rounds = 0; remaining = MODES.work.seconds; render(); } toggleBtn.addEventListener("click", () => (timerId ? pause() : start())); resetBtn.addEventListener("click", reset); render(); 

Open index.html in your browser and press Start.

Why this doesn't drift

The key line is this one:

remaining = Math.max(0, Math.ceil((endTime - Date.now()) / 1000)); 

We never subtract one second per tick. Instead we store the moment the timer should end, endTime, and on every tick we calculate how long is left from the real clock. If the browser delays a tick because the tab is in the background, the next tick still shows the correct time.

We also tick every 250 ms and not every 1000 ms. That makes the display update right on the second, instead of lagging by up to a second.

Math.ceil makes the display show 00:01 until the very end, instead of jumping to 00:00 a moment early.

How the session flow works

finish() handles what happens when time runs out:

  1. After a focus session, add one to rounds.
  2. If rounds is divisible by 4, switch to the long break. Otherwise take a short one.
  3. After any break, go back to focus.

We use rounds % 4 so the long break comes after every fourth session, not only the first.

Ideas to extend it

  • Custom durations. Add number inputs and write the values into MODES.
  • Auto-start the next session. Call start() at the end of finish().
  • Desktop notifications. Use the Notification API after asking permission.
  • Persist settings. Save durations in localStorage so they survive a refresh.
  • Visual progress. Draw a shrinking ring with an SVG circle and stroke-dashoffset.

For a different style of countdown, there are also a visual timer and a general online timer you can look at for UI ideas.

Wrapping up

The takeaways from this small project:

  • Count against a fixed end time, not against ticks.
  • Keep state in a few plain variables and have one render() function draw from them.
  • Small, single-purpose functions (start, pause, finish, reset) make a timer easy to extend.

Which feature would you add first? Tell me in the comments, and share your version if you build one.

原文:https://www.a8q9.cn/en/article/build-a-pomodoro-timer-in-vanilla-javascript-no-libraries-no-drift-09a9d0.html

相关文章