Detailed explanation of the maximum latency values of setTimeout and setInterval in JS, and setinterval latency
Preface
JavaScript provides the function of regularly executing code, called a timer.setTimeout()
AndsetInterval()
These two functions are complete. This article mainly introduces the problems related to the maximum latency of setTimeout and setInterval in JS. Let's take a look at them.
Let's look at the following code:
function update() { loadData().then(function(data) { $('#content').html(data.content); var delay = data.nextUpdateTime - new Date(); if (delay > 0) { setTimeout(update, delay); } });}
The process is very simple:After loading data through AJAX, the HTML content is updated. If the next update time is specified, the entire process is executed again through the timer at this time point.
If there is any hidden danger in this code, it isdata.nextUpdateTime
When the time difference from the current time (that is, the value of the delay variable) is small, the content is frequently updated. However, this is a normal business logic. To optimize the business logic, you must sacrifice the instant content update. However, the same problem may occur when the time difference is very large.
The following is a simulation of this scenario:
Function log () {console. log ('executed');} var nextUpdateTime = new Date (); // set it to nextUpdateTime a month later. setMonth (nextUpdateTime. getMonth () + 1); var delay = nextUpdateTime-new Date (); setTimeout (log, delay );
The original intention of this Code is to let the log function be executed in a month, but after running it, you can find that the function will be executed immediately. Why?
You can find that setTimeout uses Int32 to store the latency parameter value, that is, the maximum latency value is 2 ^ 31-1. Once the maximum value is exceeded, the effect is the same as when the latency value is 0, that is, immediate execution.
The maximum latency is nearly a month. Generally, users may not drive a webpage for a long time. If it takes so long, refresh the page:
Function update () {loadData (). then (function (data) {parameter ('{content'}.html (data. content); var delay = data. nextUpdateTime-new Date (); if (delay> 0) {// The maximum latency is one day var ONE_DAY = 24*60*60*1000; if (delay> ONE_DAY) {setTimeout (function () {window. location. reload () ;}, ONE_DAY) ;}else {setTimeout (update, delay );}}});}
The same problem exists in setInterval. This is a relatively hidden pitfall in Javascript.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.