Why does setTimeout in a while loop increment in order?












3















I had a question at the interview. I just don't get why this prints 5 6 7 8 9...



let i = 0;

while (i < 5) {
setTimeout(() => {
console.log(i++);
}, 0);
i++;
}









share|improve this question




















  • 1





    The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

    – Mark Meyer
    Dec 28 '18 at 17:54













  • When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

    – Ryan Wilson
    Dec 28 '18 at 17:54











  • You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

    – L. Figueredo
    Dec 28 '18 at 17:55


















3















I had a question at the interview. I just don't get why this prints 5 6 7 8 9...



let i = 0;

while (i < 5) {
setTimeout(() => {
console.log(i++);
}, 0);
i++;
}









share|improve this question




















  • 1





    The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

    – Mark Meyer
    Dec 28 '18 at 17:54













  • When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

    – Ryan Wilson
    Dec 28 '18 at 17:54











  • You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

    – L. Figueredo
    Dec 28 '18 at 17:55
















3












3








3








I had a question at the interview. I just don't get why this prints 5 6 7 8 9...



let i = 0;

while (i < 5) {
setTimeout(() => {
console.log(i++);
}, 0);
i++;
}









share|improve this question
















I had a question at the interview. I just don't get why this prints 5 6 7 8 9...



let i = 0;

while (i < 5) {
setTimeout(() => {
console.log(i++);
}, 0);
i++;
}






javascript settimeout






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 28 '18 at 20:15









Alireza

1,0841924




1,0841924










asked Dec 28 '18 at 17:49









doglabeldoglabel

286




286








  • 1





    The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

    – Mark Meyer
    Dec 28 '18 at 17:54













  • When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

    – Ryan Wilson
    Dec 28 '18 at 17:54











  • You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

    – L. Figueredo
    Dec 28 '18 at 17:55
















  • 1





    The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

    – Mark Meyer
    Dec 28 '18 at 17:54













  • When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

    – Ryan Wilson
    Dec 28 '18 at 17:54











  • You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

    – L. Figueredo
    Dec 28 '18 at 17:55










1




1





The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

– Mark Meyer
Dec 28 '18 at 17:54







The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start.

– Mark Meyer
Dec 28 '18 at 17:54















When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

– Ryan Wilson
Dec 28 '18 at 17:54





When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout()

– Ryan Wilson
Dec 28 '18 at 17:54













You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

– L. Figueredo
Dec 28 '18 at 17:55







You can read more about Event Loop in JS in order to understand this. I recommend this video: youtube.com/watch?v=8aGhZQkoFbQ

– L. Figueredo
Dec 28 '18 at 17:55














2 Answers
2






active

oldest

votes


















0















  • Your code starts with i = 0.

  • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.

  • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).

  • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()






share|improve this answer

































    1














    It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...






    share|improve this answer



















    • 1





      This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

      – Amy
      Dec 28 '18 at 18:01








    • 1





      johnresig.com/blog/how-javascript-timers-work

      – Amy
      Dec 28 '18 at 18:03











    • Thanks. Will check it.

      – S. Ruka
      Dec 28 '18 at 18:20













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962409%2fwhy-does-settimeout-in-a-while-loop-increment-in-order%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0















    • Your code starts with i = 0.

    • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.

    • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).

    • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()






    share|improve this answer






























      0















      • Your code starts with i = 0.

      • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.

      • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).

      • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()






      share|improve this answer




























        0












        0








        0








        • Your code starts with i = 0.

        • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.

        • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).

        • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()






        share|improve this answer
















        • Your code starts with i = 0.

        • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.

        • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).

        • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Dec 28 '18 at 18:38

























        answered Dec 28 '18 at 18:13









        MarquizzoMarquizzo

        5,65332043




        5,65332043

























            1














            It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...






            share|improve this answer



















            • 1





              This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

              – Amy
              Dec 28 '18 at 18:01








            • 1





              johnresig.com/blog/how-javascript-timers-work

              – Amy
              Dec 28 '18 at 18:03











            • Thanks. Will check it.

              – S. Ruka
              Dec 28 '18 at 18:20


















            1














            It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...






            share|improve this answer



















            • 1





              This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

              – Amy
              Dec 28 '18 at 18:01








            • 1





              johnresig.com/blog/how-javascript-timers-work

              – Amy
              Dec 28 '18 at 18:03











            • Thanks. Will check it.

              – S. Ruka
              Dec 28 '18 at 18:20
















            1












            1








            1







            It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...






            share|improve this answer













            It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 28 '18 at 17:56









            S. RukaS. Ruka

            247




            247








            • 1





              This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

              – Amy
              Dec 28 '18 at 18:01








            • 1





              johnresig.com/blog/how-javascript-timers-work

              – Amy
              Dec 28 '18 at 18:03











            • Thanks. Will check it.

              – S. Ruka
              Dec 28 '18 at 18:20
















            • 1





              This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

              – Amy
              Dec 28 '18 at 18:01








            • 1





              johnresig.com/blog/how-javascript-timers-work

              – Amy
              Dec 28 '18 at 18:03











            • Thanks. Will check it.

              – S. Ruka
              Dec 28 '18 at 18:20










            1




            1





            This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

            – Amy
            Dec 28 '18 at 18:01







            This will lower it's priority in processor. what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here.

            – Amy
            Dec 28 '18 at 18:01






            1




            1





            johnresig.com/blog/how-javascript-timers-work

            – Amy
            Dec 28 '18 at 18:03





            johnresig.com/blog/how-javascript-timers-work

            – Amy
            Dec 28 '18 at 18:03













            Thanks. Will check it.

            – S. Ruka
            Dec 28 '18 at 18:20







            Thanks. Will check it.

            – S. Ruka
            Dec 28 '18 at 18:20




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53962409%2fwhy-does-settimeout-in-a-while-loop-increment-in-order%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'