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.
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.
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
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!