How does setInterval and setTimeout work?

后端 未结 5 987
一向
一向 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:25

    JavaScript is a single-threaded scripting language, so it can execute one piece of code at a time (due to its single-threaded nature) each of these blocks of code is “blocking” the progress of other asynchronous events. This means that when an asynchronous event occurs (like a mouse click, a timer firing, or an XMLHttpRequest completing) it gets queued up to be executed later.

    setTimeout() when you use setTimeout() it will execute only when its turn comes in a queue, if an earlier event (of setTimeout) blocks due to some reason setTimeout can be delayed than the specified time in setTimeout() function. during the execution of setTimeout callback function, if any event occurs(e.g click event),it gets queued up to be executed later.

    setTimeout(function(){
      /* Some long block of code... */
      setTimeout(arguments.callee, 10);
    }, 10);
    
    setInterval(function(){
      /* Some long block of code... */
    }, 10);
    

    setInterval()

    • Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.

    • setTimeout code will always have at least a 10ms delay after the
      previous callback execution (it may end up being more, but never less) whereas the setInterval will attempt to execute a callback every 10ms regardless of when the last callback was executed.

    • If a timer is blocked from immediately executing it will be delayed
      until the next possible point of execution (which will be longer than the desired delay). Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified
      delay).

提交回复
热议问题