This article mainly introduces the JavaScript timer and the optimization method for canceling the timer. This article focuses on an optimized method for canceling the timer. if you need it, you can refer to the following common methods:
Start timer:
The code is as follows:
Window. setInterval (Method, Time)
Method is the js Method that is periodically called.
Time is the interval, in milliseconds
Cancel timer:
The code is as follows:
ClearInterval (Method );
The problem arises. ClearInterval (timerid); is used to clear data, and usually cannot be stopped immediately. how can this problem be solved?
The optimization scheme is as follows:
The code is as follows:
Var timeout = false; // The start and close buttons.
Function time ()
{
If (timeout) return;
Method ();
SetTimeout (time, 100); // time refers to itself, which is a recursive call of its own delay. 100 indicates the call interval, in milliseconds.
}
Summary
Generally, setInterval is not used, and the interval recursion of setTimeout is used instead of interval.
SetInterval will generate callback accumulation, especially when the time is short.