Why is it not accurate?

Because you are using setTimeout() or setInterval(). They cannot be trusted, there are no accuracy guarantees for them. They are allowed to lag arbitrarily, and they do not keep a constant pace but tend to drift (as you have observed).

How can I create an accurate timer?

Use the Date object instead to get the (millisecond-)accurate, current time. Then base your logic on the current time value, instead of counting how often your callback has been executed.

For a simple timer or clock, keep track of the time difference explicitly:

var start = Date.now();
setInterval(function() {
    var delta = Date.now() - start; // milliseconds elapsed since startoutput(Math.floor(delta / 1000)); // in seconds
    // alternatively just show wall clock time:
    output(new Date().toUTCString());
}, 1000); // update about every second

Now, that has the problem of possibly jumping values. When the interval lags a bit and executes your callback after 990, 1993, 2996, 3999, 5002 milliseconds, you will see the second count 0, 1, 2, 3, 5 (!). So it would be advisable to update more often, like about every 100ms, to avoid such jumps.

However, sometimes you really need a steady interval executing your callbacks without drifting. This requires a bit more advanced strategy (and code), though it pays out well (and registers less timeouts). Those are known as self-adjusting timers. Here the exact delay for each of the repeated timeouts is adapted to the actually elapsed time, compared to the expected intervals:

var interval = 1000; // ms
var expected = Date.now() + interval;
setTimeout(step, interval);
function step() {
    var dt = Date.now() - expected; // the drift (positive for overshooting)
    if (dt > interval) {
        // something really bad happened. Maybe the browser (tab) was inactive?
        // possibly special handling to avoid futile "catch up" run
    }
    … // do what is to be done

    expected += interval;
    setTimeout(step, Math.max(0, interval - dt)); // take into account drift
}
Answer from Bergi on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_timers.asp
JavaScript Timers
Timers are browser APIs that schedule callback functions to run later. They are often used as simple examples of asynchronous JavaScript.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Window › setTimeout
Window: setTimeout() method - Web APIs | MDN
June 17, 2026 - You can mitigate this risk by always ... See Security considerations for more information. The setTimeout() method of the Window interface sets a timer which executes a function or specified piece of code once the timer expires....
Discussions

How to set up a timer in javascript?
When you need to do something based on time intervals, you basically have three options: setInterval() setTimeout() requestAnimationFrame() setInterval() and setTimeout() are pretty similar. They both take a callback as their first parameter, and a timeout (in milliseconds) for how long to wait. After at least that many milliseconds have passed (it can be a bit variable, so you don't want to expect it to always be exactly that many milliseconds as it is usually +/- 4ms, but can be more if the system is slow or bogged down... potentially a lot more). The different is setInterval() will automatically call again after that many milliseconds have passed, until you call clearInterval(), wheras setTimeout() won't. You'd be tempted to use setInterval() for repeating, but I personally prefer to use setTimeout() and have it call itself again at the end of the function (makes stopping and controlling it a bit easier). However, personally, I prefer to use requestAnimationFrame() these days. With setInterval() and setTimeout(), you're basically giving it a timeout, which is functionally equivalent to running at a locked FPS for a game. If you want to run as fast as possible, use requestAnimationFrame(). It takes a callback as a function and will trigger it basically as soon as possible. It works like setTimeout() in that you'll need to call it again at the end of your function to get it to loop. You basically use all three of these the same way: Keep track of the last time you called them Get the current time Get the delta (how much time has passed since the last call) Do something with delta (setTimeout() or requestAnimationFrame()) Call again if necessary. Something like this: let lastTime = Date.now(); const tick = () => { const now = Date.now(); const delta = now - lastTime; lastTime = now; // Now do something with delta, which contains the number of milliseconds since this function was last called. // or setTimeout() for fixed FPS requestAnimationFrame(tick); }; tick(); // initial call to kick things off For your timer bit, I would just set a boolean like running to true on the key press and set the time to zero (or to some value if counting down), then each tick(), add (or subtract for countdown) the delta from time. More on reddit.com
🌐 r/learnjavascript
5
3
November 2, 2021
Beginner JavaScript Timer
Looks really cool! I like it, simple and elegant. Only thing I’d suggest is to fix how it looks on mobile view. The numbers were too far down on my phone but everything else really nice. :) More on reddit.com
🌐 r/FreeCodeCamp
5
22
March 14, 2022
Is it possible to have an accurate timer in javascript
Web Audio is what you need! Anything like setTimeout, setInterval etc is the wrong choice as it runs in the same thread as your UI, so it can be delayed by rendering, clicking, scrolling and so on. Web Audio contexts run in a different thread so this isn’t a problem. More on reddit.com
🌐 r/learnjavascript
11
18
October 24, 2022
I made a countdown timer but it's not counting properly
quarrelsome simplistic dazzling connect shame profit cats zesty birds upbeat This post was mass deleted and anonymized with Redact More on reddit.com
🌐 r/learnjavascript
6
13
October 28, 2022
Top answer
1 of 16
273

Why is it not accurate?

Because you are using setTimeout() or setInterval(). They cannot be trusted, there are no accuracy guarantees for them. They are allowed to lag arbitrarily, and they do not keep a constant pace but tend to drift (as you have observed).

How can I create an accurate timer?

Use the Date object instead to get the (millisecond-)accurate, current time. Then base your logic on the current time value, instead of counting how often your callback has been executed.

For a simple timer or clock, keep track of the time difference explicitly:

var start = Date.now();
setInterval(function() {
    var delta = Date.now() - start; // milliseconds elapsed since startoutput(Math.floor(delta / 1000)); // in seconds
    // alternatively just show wall clock time:
    output(new Date().toUTCString());
}, 1000); // update about every second

Now, that has the problem of possibly jumping values. When the interval lags a bit and executes your callback after 990, 1993, 2996, 3999, 5002 milliseconds, you will see the second count 0, 1, 2, 3, 5 (!). So it would be advisable to update more often, like about every 100ms, to avoid such jumps.

However, sometimes you really need a steady interval executing your callbacks without drifting. This requires a bit more advanced strategy (and code), though it pays out well (and registers less timeouts). Those are known as self-adjusting timers. Here the exact delay for each of the repeated timeouts is adapted to the actually elapsed time, compared to the expected intervals:

var interval = 1000; // ms
var expected = Date.now() + interval;
setTimeout(step, interval);
function step() {
    var dt = Date.now() - expected; // the drift (positive for overshooting)
    if (dt > interval) {
        // something really bad happened. Maybe the browser (tab) was inactive?
        // possibly special handling to avoid futile "catch up" run
    }
    … // do what is to be done

    expected += interval;
    setTimeout(step, Math.max(0, interval - dt)); // take into account drift
}
2 of 16
40

I'ma just build on Bergi's answer (specifically the second part) a little bit because I really liked the way it was done, but I want the option to stop the timer once it starts (like clearInterval() almost). Sooo... I've wrapped it up into a constructor function so we can do 'objecty' things with it.

1. Constructor

Alright, so you copy/paste that...

/**
 * Self-adjusting interval to account for drifting
 * 
 * @param {function} workFunc  Callback containing the work to be done
 *                             for each interval
 * @param {int}      interval  Interval speed (in milliseconds)
 * @param {function} errorFunc (Optional) Callback to run if the drift
 *                             exceeds interval
 */
function AdjustingInterval(workFunc, interval, errorFunc) {
    var that = this;
    var expected, timeout;
    this.interval = interval;

    this.start = function() {
        expected = Date.now() + this.interval;
        timeout = setTimeout(step, this.interval);
    }

    this.stop = function() {
        clearTimeout(timeout);
    }

    function step() {
        var drift = Date.now() - expected;
        if (drift > that.interval) {
            // You could have some default stuff here too...
            if (errorFunc) errorFunc();
        }
        workFunc();
        expected += that.interval;
        timeout = setTimeout(step, Math.max(0, that.interval-drift));
    }
}

2. Instantiate

Tell it what to do and all that...

// For testing purposes, we'll just increment
// this and send it out to the console.
var justSomeNumber = 0;

// Define the work to be done
var doWork = function() {
    console.log(++justSomeNumber);
};

// Define what to do if something goes wrong
var doError = function() {
    console.warn('The drift exceeded the interval.');
};

// (The third argument is optional)
var ticker = new AdjustingInterval(doWork, 1000, doError);

3. Then do... stuff

// You can start or stop your timer at will
ticker.start();
ticker.stop();

// You can also change the interval while it's in progress
ticker.interval = 99;

I mean, it works for me anyway. If there's a better way, lemme know.

🌐
Reddit
reddit.com › r/learnjavascript › how to set up a timer in javascript?
r/learnjavascript on Reddit: How to set up a timer in javascript?
November 2, 2021 -

So i have a HTML game, that basically return a score .

so i need to

1.start a timer at first key press.

2.stop and store the timer once score

3. reset the timer and the game.

how do i go a set up a timer in such situations?

Top answer
1 of 2
2
When you need to do something based on time intervals, you basically have three options: setInterval() setTimeout() requestAnimationFrame() setInterval() and setTimeout() are pretty similar. They both take a callback as their first parameter, and a timeout (in milliseconds) for how long to wait. After at least that many milliseconds have passed (it can be a bit variable, so you don't want to expect it to always be exactly that many milliseconds as it is usually +/- 4ms, but can be more if the system is slow or bogged down... potentially a lot more). The different is setInterval() will automatically call again after that many milliseconds have passed, until you call clearInterval(), wheras setTimeout() won't. You'd be tempted to use setInterval() for repeating, but I personally prefer to use setTimeout() and have it call itself again at the end of the function (makes stopping and controlling it a bit easier). However, personally, I prefer to use requestAnimationFrame() these days. With setInterval() and setTimeout(), you're basically giving it a timeout, which is functionally equivalent to running at a locked FPS for a game. If you want to run as fast as possible, use requestAnimationFrame(). It takes a callback as a function and will trigger it basically as soon as possible. It works like setTimeout() in that you'll need to call it again at the end of your function to get it to loop. You basically use all three of these the same way: Keep track of the last time you called them Get the current time Get the delta (how much time has passed since the last call) Do something with delta (setTimeout() or requestAnimationFrame()) Call again if necessary. Something like this: let lastTime = Date.now(); const tick = () => { const now = Date.now(); const delta = now - lastTime; lastTime = now; // Now do something with delta, which contains the number of milliseconds since this function was last called. // or setTimeout() for fixed FPS requestAnimationFrame(tick); }; tick(); // initial call to kick things off For your timer bit, I would just set a boolean like running to true on the key press and set the time to zero (or to some value if counting down), then each tick(), add (or subtract for countdown) the delta from time.
2 of 2
1
var myTimer= setInterval(myTimer, 1000); //starts timer var time = 0; //time function myTimer() { time++; document.getElementById("timer").innerHTML = time; //displays time } function stopTimer() { clearInterval(myTimer); //stops timer }
🌐
Medium
devdeepakkumar.medium.com › the-javascript-timers-that-nobody-actually-explains-1d4d8e169000
The JavaScript Timers That Nobody Actually Explains | by Deepak Kumar | Medium
May 2, 2026 - If you somehow ran pure V8 (the JavaScript engine) without any host environment, setTimeout wouldn't exist. ... You pass it a callback and a delay in milliseconds. The browser puts a timer in the background, counts down, and when the timer fires, it pushes your callback into the event queue.
🌐
Medium
medium.com › @teamtechsis › timers-and-intervals-in-javascript-c5f4b3450486
Timers and Intervals in JavaScript | by Natasha Ferguson | Medium
December 27, 2022 - const timer = document.getElementById('timer'); let currentTime = 10; function countDown() { currentTime-- timer.textContent = currentTime if (currentTime === 0 ) { clearInterval(timerID) alert('Game over!') } } let timerID = setInterval(countDown, 1000)
Find elsewhere
🌐
DEV Community
dev.to › oculus42 › javascript-timers-intervals-5fnl
JavaScript Timers & Intervals - DEV Community
February 14, 2025 - The code to test timer variation is not particularly pretty, but it breaks down into a few pieces. The intervalFor function wraps setInterval so that the test will eventually end. It also executes our report function as a callback.
🌐
Kirupa
kirupa.com › html5 › timers_js.htm
Timers in JavaScript
Learn how to delay execution of your code to the specified (or right) time by using setTimeout, setInterval, and requestAnimationFrame.
🌐
SitePoint
sitepoint.com › blog › programming › creating accurate timers in javascript
Creating Accurate Timers in JavaScript — SitePoint
November 6, 2024 - However, these methods are not always accurate due to JavaScript’s single-threaded nature and the browser’s event loop. To create a more accurate timer, you can use the performance.now() method, which provides a high-resolution timestamp, allowing for more precise timing operations.
🌐
Udacity
udacity.com › blog › javascript-timers-wait-functions
Javascript Timers and Javascript Wait Functions: Handling Execution Times | Udacity
September 8, 2021 - Javascript timers, also known as wait functions, provide the ability to delay Javascript code execution for specific intervals of time.
🌐
DZone
dzone.com › coding › javascript › how javascript timers work
How JavaScript Timers Work
May 22, 2023 - In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread, asynchronous events (such as mouse clicks and timers) are only run when there's been an ...
🌐
GitHub
gist.github.com › evsar3 › da7ea74e775f12bd553e104ecc25d5d4
Javascript Timer class | Javascript setInterval extension · GitHub
// Basic var timer = new Timer(1000, function () { console.log("Tick Tac!"); }); // Call the callback imediatelly var timer = new Timer(1000, function () { console.log("Tick Tac!"); }).execute();
🌐
freeCodeCamp
freecodecamp.org › news › javascript-timer-how-to-set-a-timer-function-in-js
JavaScript Timer – How to Set a Timer Function in JS
September 16, 2024 - In Javascript, the timer function prevents your code from running everything at once when an event triggers or the page loads. This gives you more control over the timing of your program's actions and can enhance the user experience by creating ...
🌐
Medium
abhi9bakshi.medium.com › why-javascript-timer-is-unreliable-and-how-can-you-fix-it-9ff5e6d34ee0
Why Javascript timer is unreliable, and how can you fix it | by Abhinav Bakshi | Medium
July 23, 2018 - If you are a Javascript developer, at some point in your career, you must have used setTimeout or setInterval. They are extremely handy if you wish to perform an operation after some time, or you want to repeat an operation multiple times after a certain interval. So when I stumbled upon the task of creating a countdown timer and stopwatch in one of my projects, setInterval felt right at home to me.
🌐
Logwork
logwork.com › countdown-timer
Free HTML Countdown Timer Embed Widget Code for Website
Free HTML countdown timer embed widget for website. Create a countdown clock timer widget code. Embed countdown timer generator.
🌐
Mentimeter
mentimeter.com › home › audience response software that will engage your audience › live quiz maker for presentations & classrooms
Live Quiz Maker for Presentations & Classrooms - Mentimeter
Create live, interactive quizzes with Mentimeter. Test knowledge, show leaderboards, and make learning fun with templates and real-time scoring.
🌐
Edureka
edureka.co › blog › timer-in-javascript
All you Need to Know about Timers in JavaScript - Edureka
February 25, 2025 - Here is the code for Timers in JavaScript that sets the timer of 2 minutes and when the times up the Page alert “times up”. The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
🌐
Node.js
nodejs.org › api › timers.html
Timers | Node.js v26.5.0 Documentation
The timer module exposes a global API for scheduling functions to be called at some future period of time.