JavaScript timer and optimized cancel timer method, javascript Timer
Common Methods:
Start Timer:
Copy codeThe 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:
Copy codeThe 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:
Copy codeThe 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.