Overview of this article: This article mainly introduces the method of implementing timed and fixed-point execution through JS and executing a certain function at a fixed time. For example, a method that executes at the next hour, at each hour, and is executed regularly every 10 minutes.
There are two timer methods in JavaScript: setTimeout() and setInterval().
Both methods can be used to implement JavaScript execution after a fixed time period. In fact, the syntax of setTimeout and setInterval is the same. They all have two parameters, one is the code string to be executed, or the function name, and the other is a time interval in milliseconds. After that time period, that piece of code will be executed.
However, there are still differences between these two functions:
① setInterval() will execute the code or function to be executed regularly multiple times. After that fixed time interval, it will automatically execute the code repeatedly.
② setTimeout() will only execute that code or specified function once.
1. Loop execution
The following JS statement implements the circuitExecute() method every ten minutes.
//The loop is executed every ten minutes. The first execution is 10 minutes later. setInterval("circulateExecute();",10*60*1000);//Execute once in 10 minutes2. The next hour, or a certain moment, execute at a fixed point
The following javascript code implements the execution of the nextIntegralPointAfterLogin() method at the next point at the current moment.
var date = new Date();//The present moment var dateIntegralPoint = new Date();//The next hour point at the user's login moment can also be set to a fixed time dateIntegralPoint.setHours(date.getHours()+1);//The number of hours is increased by 1dateIntegralPoint.setMinutes(0);dateIntegralPoint.setSeconds(0);setTimeout("nextIntegralPointAfterLogin();",dateIntegralPoint-date);//The next hour point after the user login is executed.3. Each point is executed in a fixed point
After executing the nextIntegralPointAfterLogin() function at the next hour point as described above, in order to implement the execution of a certain function at each hour point, you can write the following code in the nextIntegralPointAfterLogin() function.
function nextIntegralPointAfterLogin(){ IntegralPointExecute();//The function executed at an hour is called at each hour setInterval("IntegralPointExecute();",60*60*1000);//Execute once in an hour, then the next hour and the next hour will be executed} Note: Due to the error of JS calculation and the execution process that requires a certain amount of time, the above-mentioned timed and fixed-point execution method may have an error of one or two seconds.The above detailed explanation of the use of JS timer, timed, fixed time, and loop execution is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.