I used to read this: SetTimeout can complete the setinterval function, and settimeout is to perform an automatic termination, SetInterval does not need to stop manually so it is recommended to use settimeout instead of setinterval so that code avoids the last-expected execution loop
On the internet to find a lot of countdown, found to be used settimeout
Shaped like:
The code is as follows |
Copy Code |
function Docount () { Reduce the time that is passed in "Suppose" This function executes 2S to complete } SetTimeout (cc,1000)
function cc () { DoSomething (); SetTimeout (cc,1000) } |
Some people say that the browser processing JS time single process, now assume that dosomething executed 2 seconds (this is a hypothetical, actually impossible), and so dosomething execution, and then call settimeout this to do the countdown is not allowed?
/
Ask again.
The code is as follows |
Copy Code |
SetInterval ( function () { DoSomething () },1000 ) |
Instead, SetInterval is forced to perform dosomething every 1 seconds, assuming DoSomething also takes 2 seconds, then isn't
Code queue in the execution of dosomething process, found setinterval to time, but found Doshoething did not finish, jumped out of the current setinterval implementation?
Ask a bit messy, just find why everybody use settimeout do timer, I feel setinterval is not easier, and more accurate (after all general dosomethis almost execute on a few Ms time)
Summary
The code that settimeout recursively executes must be the last time it is executed and the grid will execute again.
SetTimeout: The delay time is 1 seconds to execute, the code to execute requires 2 seconds to execute, and that code last and next time is 3 seconds. Not the one we imagined every 1 seconds.
SetInterval is queued for execution.
than The imitation said: SetInterval Each execution time is 1 seconds, and the execution of the Code requires 2 seconds to execute, it is still every time to execute this code, the last time did not finish the code will be queued, the previous execution of the next time to execute immediately, so that the actual execution of the interval of 2 seconds
In this way, it seems to me that if the setinterval executes longer than the interval of each execution, it makes no sense, and the team gets longer and the memory is eaten up. If one of the executions is stuck, the program will be blocked.
and settimout The following writing does not appear because of a blocked, and the memory is eaten up the problem. But the timing of the execution is inaccurate and determined.