Perfect Timer for the Web

Perfect Timer for the Web

⏰ Thick
⌛ now?


... tik, tok
Tik
Tok

Perfect Timer for the Web

Kacper Walczak · 10-08-2024

  • Learn how to create perfect 10min, etc. timer for your apps in typescript.

Last edit: 18-08-2024, Kacper Walczak

Introduction

Why do we need Perfect Timer?

There is one answer -> setTimeout(() => {...}, 1000) can be activated after 1002ms or 1008ms on another computer instead of 1000ms ;)

That's why we need to check whether 1sec is completed or not by iterating few times and proper checking e.g. 4 times a sec.

Timer code

I have used this code to ensure better time management for PsyApp(there were tests when players needed to press appropriate keys in realtime and exact 10min -> reason why I needed to check time).

startTimer function

lib/timer.ts
type IntervalID = number;
 
interface TimerObj {
    resume(): void;
    pause(): void;
    step(): number;
}
 
const startTimer = (seconds: number, oncomplete?: () => void, container?: string): TimerObj  => {
    let startTime: number;
    let timer: IntervalID;
    let ms = seconds * 1000;
    const display = container ? document.getElementById(container) : null; // if we pass container = 'your_element_id' it will allow us to print: '0:02' there
 
    const timerObj: TimerObj = {
        resume() {
            startTime = new Date().getTime();
            // lower numbers are more accurate, but more CPU-expensive
            timer = setInterval(this.step, 250); // adjust this number to affect granularity
        },
        pause() {
            ms = this.step();
            clearInterval(timer);
        },
        step() {
            const now = Math.max(0, ms - (new Date().getTime() - startTime));
    
            if (display) {
                const m = Math.floor(now / 60000);
                let s = Math.floor(now / 1000) % 60 as number | string;
                s = ((s as number) < 10 ? '0' : '') + s;
                display.innerHTML = m + ':' + s;
            }
    
            if (now === 0) {
                clearInterval(timer);
                this.resume = () => { };
                if (oncomplete) { oncomplete(); }
            }
            return now;
        }
    };
 
    timerObj.resume(); // initial run
    return timerObj;
};

Usage

lib/timer.ts
// when we want to listen when counting has ended
const tenSeconds = 10;
const timer = startTimer(tenSeconds, () => console.log('on:completed'));
 
// when we want to provide HTML element to paste in timer like '0:10'
const tenMinutes = 60 * 10;
const timerShownOnScreen = startTimer(tenMinutes, () => console.log('on:completed'), 'tag_element_id_here');
 
// you can even pause on specific scenarios, here simple delay just for showcase
setTimeout(() => timerShownOnScreen.pause(), 2000);
 
// after resuming we will start from place where you have paused
setTimeout(() => timerShownOnScreen.resume(), 4000);

Output

# example output with console.log inside step() function...
0:02
0:02
0:02
0:01
0:01
0:01
0:01
0:00
0:00
0:00
0:00
0:00
on:completed

Conclusion

This way we can properly manage time in Javascript.

READ

Latest readings

  • Readings are sites which will help you with detailed

  • information about given topic. Read latest ones from Learn.

AI

06-03-2026

Local Voice Assistant with Ollama
  • Build your own local voice assistant powered by Ollama.

AI

06-03-2026

AI YouTube Thumbnail Generator
  • Generate YouTube thumbnails with FastAPI and Ollama.

Architecture

05-09-2024

Graph DB usage comparison
  • Compare Neo4j and Tigergraph databases, which is easier to work with, etc.