setTimeout(fn,200)
, does the time specified here mean that it is calculated as soon as the program starts running? Or should we wait until the main thread's task is completed and call back the asynchronous task list before starting the calculation?
世界只因有你2017-07-05 11:05:30
This is a bit complicated to explain
First of all, you must understand that Javascript is single-threaded. Single-threading means that all tasks need to be queued. Then all tasks will be divided into two categories: synchronous tasks and asynchronous tasks! Synchronous tasks: Tasks executed on the main thread will only execute the next task after the previous task is completed! Asynchronous tasks: Tasks that do not enter the main thread but enter the "task queue". When the tasks on the main thread are completed, the main thread will execute the "task queue".
For setTimeout(fn,200)
, when it reaches 200ms, fn
will be put into the "task queue", and the "task queue" must wait until the existing code of the main thread is executed before fn
, so when the program executes to the line setTimeout(fn,200)
, the time starts to be calculated, but the actual execution of fn
is not necessarily after 200ms, it may be after a longer time (depending on the host execution time of synchronized code on a thread).
欧阳克2017-07-05 11:05:30
Simply putsetTimeout(fn,200)
You need to wait until the current function call stack (synchronization task on the main process) is cleared before starting execution. It will be executed in the next round of event loop (the main thread reads events from the "task queue" ) is executed at the beginning, setTimeout
only inserts the event into the "task queue". The time set here is the interval relative to the time at the start of the next round of event loop.