admin管理员组文章数量:1393037
I've been learning about setTimeout
and synchronous versus asynchronous code, I was watching a tutorial video where they showed various functions being called and added to the call stack, e.g. a function to simply add 2 numbers.
However for setTimeout
they didn't show that when this was invoked that it was being added to the call stack, I understand that this fires up a web API and that the callback is added to a queue but I'm curious if in the moment that setTimeout
is being executed by the JS engine, is it added to the call stack or not?
I've been learning about setTimeout
and synchronous versus asynchronous code, I was watching a tutorial video where they showed various functions being called and added to the call stack, e.g. a function to simply add 2 numbers.
However for setTimeout
they didn't show that when this was invoked that it was being added to the call stack, I understand that this fires up a web API and that the callback is added to a queue but I'm curious if in the moment that setTimeout
is being executed by the JS engine, is it added to the call stack or not?
3 Answers
Reset to default 7in the moment that
setTimeout
is being executed by the JS engine, is it added to the call stack or not?
It is. And it is popped from the call stack as soon as the callback is registered, so this hardly takes any time.
When the given delay has passed, the callback will be queued. Then when the call stack is empty, JS will process the event queue, and the callback will be called. Also this callback will be added to the call stack.
Just note that setTimeout
and the callback will not be added to the call stack cumulative. It is guaranteed that the call stack will be emptied first before the callback will be pushed unto it.
Yes, after the time set in timeout passes, the callback is pushed to the call stack & executed.
Actually, the only way for a JS function to execute is to pass through the call stack.
Here is a good visualization tool called loupe by Philip Roberts that may help in understanding the call stack & things related to it.
setTimeout would be pushed to the call stack and then popped. When it is popped, it is sent to a browser API (if the code is executed in the browser). The API waits till the specified time is done and the callback is sent to the event queue. When the call stack is empty, the event loop will take the callback from the event queue (assuming it was next in line in the queue) and put it to the stack when it then gets executed.
本文标签: javascriptDoes setTimeout get added to the call stackStack Overflow
版权声明:本文标题:javascript - Does setTimeout get added to the call stack? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744644109a2617294.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论