javascript - From what time period does the delay time of setTimeout start?
女神的闺蜜爱上我
女神的闺蜜爱上我 2017-07-05 11:03:30
0
3
1301

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?

女神的闺蜜爱上我
女神的闺蜜爱上我

reply all(3)
世界只因有你

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).

学霸

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.

巴扎黑

Start timing when setTimeout(fn,200) is called.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template