How does setInterval and setTimeout work?

后端 未结 5 994
一向
一向 2020-11-30 00:57

I was in an awkward situation,

I am working with pure JavaScript for almost 3 years, and I know that JavaScript is single-threaded language

5条回答
  •  天涯浪人
    2020-11-30 01:06

    How setTimeout / setInterval work's in JavaScript

    Browser has API for Timer function just like API for event ex.

    'click'

    'scroll'

    Assume that you have following code in your application

    function listener(){
        ...
    }
    
    setTimeout(listener, 300)
    
    function foo(){
        for(var i = 0; i < 10000; i++){
            console.log(i)
        }
    }
    
    foo()
    

    See How Function Execution work's in javascript

    At this point as per our code we wrote above our call stack will look like

    Call Stack -> foo

    And let's assume that foo will take 1s to complete it's execution, as we already defined 1 timeout in our code and we are running it before "foo" complete's it's execution i.e at 300ms

    What will happen then ?

    Does javascript stop executing foo and start executing setTimeout ?

    No

    As we already know javascript is single threaded so it has to complete execution of foo before moving ahead, but how does browser insure that after execution of foo the "setTimeout" will execute ?

    Here javascript magic comes into picture

    When 300ms is expired the browser "Timer API" kicks in and put the timeout handler into "Message Queue"

    At this point "Message Queue" in above image will look like

    Message Queue -> setTimout:listner

    And

    Call Stack -> foo

    And when "Call Stack" becomes empty i.e foo completes it's execution the "Event Loop" as shown in the image will take the message from message queue and push it into stack

    The only job of "Event Loop" is when "Call Stack" becomes empty and "Message Queue" has entry in it then dequeue the message form "Message Queue" and push it into "Call Stack"

    At this point Message Queue in above image will look like

    Message Queue ->

    And

    Call Stack -> listener

    And that's how setTimeout and setInterval works, even though we specify 300 ms in the setTimeout it will execute after "foo" completes it's execution in this case i.e after 1s. And that's why timer specified in setTimeout/setInterval indicates "Minimum Time" delay for execution of function.

提交回复
热议问题