Why does setTimeout in a while loop increment in order?
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
add a comment |
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
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
add a comment |
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
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
javascript settimeout
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
- Your code starts with
i = 0. - When it enters the
whileloop, it'll be incremented to1, 2, 3, 4and stop when it reaches5. - The
setTimeoutfunction is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (thewhileloop). - Since
iwas at5when thewhileloop ended, thesetTimeoutfunctions will pick it up from there, outputting its value and incrementing it by one on each subsequentconsole.log()
add a comment |
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...
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
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
- Your code starts with
i = 0. - When it enters the
whileloop, it'll be incremented to1, 2, 3, 4and stop when it reaches5. - The
setTimeoutfunction is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (thewhileloop). - Since
iwas at5when thewhileloop ended, thesetTimeoutfunctions will pick it up from there, outputting its value and incrementing it by one on each subsequentconsole.log()
add a comment |
- Your code starts with
i = 0. - When it enters the
whileloop, it'll be incremented to1, 2, 3, 4and stop when it reaches5. - The
setTimeoutfunction is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (thewhileloop). - Since
iwas at5when thewhileloop ended, thesetTimeoutfunctions will pick it up from there, outputting its value and incrementing it by one on each subsequentconsole.log()
add a comment |
- Your code starts with
i = 0. - When it enters the
whileloop, it'll be incremented to1, 2, 3, 4and stop when it reaches5. - The
setTimeoutfunction is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (thewhileloop). - Since
iwas at5when thewhileloop ended, thesetTimeoutfunctions will pick it up from there, outputting its value and incrementing it by one on each subsequentconsole.log()
- Your code starts with
i = 0. - When it enters the
whileloop, it'll be incremented to1, 2, 3, 4and stop when it reaches5. - The
setTimeoutfunction is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (thewhileloop). - Since
iwas at5when thewhileloop ended, thesetTimeoutfunctions will pick it up from there, outputting its value and incrementing it by one on each subsequentconsole.log()
edited Dec 28 '18 at 18:38
answered Dec 28 '18 at 18:13
MarquizzoMarquizzo
5,65332043
5,65332043
add a comment |
add a comment |
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...
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
add a comment |
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...
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
add a comment |
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...
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...
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
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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