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.