Home >Web Front-end >JS Tutorial >How Can I Create Accurate JavaScript Timers That Avoid Drifting?

How Can I Create Accurate JavaScript Timers That Avoid Drifting?

Linda Hamilton
Linda HamiltonOriginal
2024-12-14 16:01:12529browse

How Can I Create Accurate JavaScript Timers That Avoid Drifting?

Creating Accurate JavaScript Timers

Timers play a crucial role in JavaScript for scheduling tasks and implementing real-time functionality. However, ensuring the accuracy of timers can be challenging due to the asynchronous nature of JavaScript execution.

Inaccuracy of setInterval/setTimeout

The code snippet you provided utilizes the setInterval function to increment a counter every second. However, you observed that after 3600 seconds, the counter only reached about 3500 seconds. This is because setInterval and setTimeout are not inherently accurate. They are prone to delays and drifting over time.

Accurate Timing with the Date Object

To create an accurate timer, it's recommended to use the Date object instead. The Date object allows you to obtain the current time with millisecond precision. You can base your timer's logic on the difference between the current time and a start time, like so:

var start = Date.now();
setInterval(function() {
    var delta = Date.now() - start; // milliseconds elapsed since start
    ...
    output(Math.floor(delta / 1000)); // in seconds
}, 1000); // update about every second

Self-Adjusting Timers

For timer applications that require a constant interval without drifting, self-adjusting timers are a better option. They dynamically adjust the delay between timeouts based on the actual elapsed time. This approach ensures that the timer stays on track:

var interval = 1000; // ms
var expected = Date.now() + interval;
setTimeout(step, interval);
function step() {
    var dt = Date.now() - expected; // the drift (positive for overshooting)
    ... // do what is to be done
    expected += interval;
    setTimeout(step, Math.max(0, interval - dt)); // take into account drift
}

The above is the detailed content of How Can I Create Accurate JavaScript Timers That Avoid Drifting?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn