SetTimeout and SetInterval, these two JS functions are used to execute on a timed basis. SetTimeout executes once, setinterval executes multiple times.
The problem appears today, using setinterval Yes, set execution speed to 1ms. There was a delay in the setinterval. It is not strictlyperformed at a speed of 1 Ms.
varspeed1=1; Task1=setinterval (function () {varVal1=parseint (document.getElementById ('Font1'). InnerHTML); if(val1>0&& val1<= the) {Val1--; document.getElementById ('Font1'). innerhtml=Val1; }Else{clearinterval (TASK1); }},speed1);
The reason for the problem is to start with JavaScript's single-threaded mechanism. For a long-time task to set a short time interval, the delay may occur due to the execution of continuous iterations before the first execution completes. Because SetInterval's callback function is not executed immediately after the time, it is not executed until the system resources have been idle. The next trigger time starts the timing after the setinterval callback function is completed, so if the calculations performed within the setinterval are too time-consuming, Or if there are other time-consuming tasks in the execution, SetInterval's timing will be more and more inaccurate and the delay is severe.
What settimeout and SetInterval call "asynchronous invocation" is actually implemented by inserting code snippets into the execution queue of the code.
And how to calculate the insertion point in time? It's natural to use what we call a timer. When executing settimeout and setinterval, the timer "accurately" locates the insertion point of the code based on the time you set. When the queue "normally" executes to the insertion point, it triggers the timer callback, which is the callback function we set. In fact settimeout and setinterval just simply insert code into the Code queue to implement deferred execution (or asynchronous execution) of the code. The so-called Async is just an illusion-it's also running on a thread!
Understanding SetTimeout and SetInterval