Detailed Explanation of Maximum Delay Values of setTimeout and setInterval in JS

  • 2021-07-21 06:39:34
  • OfStack

Preface

JavaScript provides the function of executing code regularly, called timer (timer), which is mainly composed of setTimeout() And setInterval() These two functions are completed. This article mainly introduces the related problems about the maximum delay value of setTimeout and setInterval in JS. Friends who need it will learn from it.

Let's look at this one piece of code first:


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: update the content of HTML after loading data through AJAX; If the next update time is specified, the whole process is executed once again at that time point through the timer.

If there is anything wrong with this code, it is data.nextUpdateTime When the time difference from the current time (that is, the value of the delay variable) is relatively small, the content will be updated frequently. However, this is normal business logic, and the immediacy of content update can only be sacrificed to optimize it. However, what I want to say here is that when the time difference is very large, the same problem will occur.

Let's simulate this scenario 1:


function log() {
 console.log('executed');
}

var nextUpdateTime = new Date();
//  Set to 1 Months later 
nextUpdateTime.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 after 1 month, but you can find that the function will be executed immediately after running 1. Why is this happening?

Search 1 and find that setTimeout uses Int32 to store the delay parameter value, that is to say, the maximum delay value is 2 31-1. Once the maximum value is exceeded, the effect will be the same as if the delay value is 0, that is, it will be executed immediately.

This maximum delay value is close to 1 month. Under normal circumstances, users will not open a webpage for a long time. If it has been opened for so long, refresh it for 1 time:


function update() {
 loadData().then(function(data) {
  $('#content').html(data.content);
  var delay = data.nextUpdateTime - new Date();
  if (delay > 0) {
   //  Limit the maximum delay value to 1 Days 
   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 pit in Javascript.

Summarize

The above is the whole content of this article. I hope the content of this article can bring 1 certain help to everyone's study or work. If you have any questions, you can leave a message for communication.


Related articles: