JavaScript EventLoop
转自:http://cek.io/blog/2015/12/03/event-loop/
What is JavaScript
What is JavaScript anyway? Some words:
- It’s a single-threaded, non-blocking, asynchronous, concurrent language”
- It has a call stack, an event loop, a callback queue, some other apis and stuff
If you’re like me (or Philip Roberts, it seems), these words themselves don’t mean a ton. So let’s parse that out.
JavaScript Runtimes
JavaScript runtimes (like V8) have a heap (memory allocation) and stack (execution contexts). But they don’t have setTimeout
, the DOM, etc. Those are web APIs in the browser.
JavaScript as we know it
JavaScript in the browser has:
- a runtime like V8 (heap/stack)
- Web APIs that the browser provides, like the DOM, ajax, and
setTimeout
- a callback queue for events with callbacks like
onClick
,onLoad
,onDone
- an event loop
What’s the call stack?
JavaScript is single-threaded, meaning it has a single call stack, meaning it can do one thing at a time. The call stack is basically a data structure which records where in the program we are. If we step into a function, we push something onto the stack. If we return from a function, we pop off the top of the stack.
When our program throws an error, we see the call stack in the console. We see the state of the stack (which functions have been called) when that error happened.
Blocking
An important question that this relates to: what happens when things are slow? In other words, blocking. Blocking doesn’t have a strict definition; really it’s just things that are slow. console.log
isn’t slow, but while
loops from 1 to 1,000,000,000, image processing, or network requests are slow. Those things that are slow and on the stack are blocking.
Since JS is single-threaded, we make a network request and have to wait until it’s done. This is a problem in the browser—while we wait on a request, the browser is blocked (can’t click things, submit forms, etc.). The solution is asynchronous callbacks.
Concurrency, where we realize there’s a lie above
It’s a lie that JavaScript can only do one thing at a time. It’s true: JavaScript the runtime can only do one thing at a time. It can’t make an ajax request while doing other code. It can’t do a setTimeout
while doing other code. But we can do things concurrently, because the browser is more than the runtime (remember the grainy image above).
The stack can put things into web APIs, which (when done) push callbacks onto task queue, and then…the event loop. Finally we get to the event loop. It’s the simplest little piece in this equation, and it has one very simple job. Look at the stack and look at the task queue; if the stack is empty, it takes the first thing off of the queue and pushes it onto the stack (back in JS land, back inside V8).
Louping it all together
Philip built an awesome tool to visualize all of this, called Loupe. It’s a tool that can visualize the JavaScript runtime at runtime.
Let’s use it to look at a simple example: logging a few things to the console, with one console.log
happening asynchronously in a setTimeout
.
What’s actually happening here? Let’s go through it:
- We step into the
console.log('Hi');
function, so it’s pushed onto the call stack. console.log('Hi');
returns, so it’s popped off the top of the stack.- We step into the
setTimeout
function, so it’s pushed onto the call stack. setTimeout
is part of the web API, so the web API handles that and times out the 2 seconds.- We continue our script, stepping into the
console.log('Everybody')
function, pushing it onto the stack. console.log('Everybody')
returns, so it’s popped off the stack.- The 2-second timeout completes, so the callback moves to the callback queue.
- The event loop checks if the call stack is empty. If it were not empty, it would wait. Because it is empty, the callback is pushed onto the call stack.
console.log('Everybody')
returns, so it’s popped off the call stack.
An interesting aside: setTimeout(function(...), 0)
. setTimeout
with 0 isn’t necessarily intuitive, except when considered in the context of call stack and event loop. It basically defers something until the stack is clear.
JavaScript EventLoop的更多相关文章
- 对javascript EventLoop事件循环机制不一样的理解
前置知识点: 浏览器原理,浏览器内核5种线程及协作,JS引擎单线程设计推荐阅读: 从浏览器多进程到JS单线程,JS运行机制最全面的一次梳理 [FE]浏览器渲染引擎「内核」 js异步编程,Promise ...
- 初识JavaScript EventLoop
Event Loop指的是计算机系统的一种运行机制.JavaScript采用此机制解决单线程引发相关问题 在浏览器中的web应用会涉及到.JavaScript引擎.WebAPI.Event Loop. ...
- JavaScript的sleep实现--Javascript异步编程学习
一.原始需求 最近在做百度前端技术学院的练习题,有一个练习是要求遍历一个二叉树,并且做遍历可视化即正在遍历的节点最好颜色不同 二叉树大概长这个样子: 以前序遍历为例啊, 每次访问二叉树的节点加个sle ...
- JavaScript Concurrency model and Event Loop 并发模型和事件循环机制
原文地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop JavaScript 有一个基于 event loop 的 ...
- javascript运行时中的堆栈和队列
下面是一个理论上的模型,js引擎着重实现和优化了描述的这几个语义 可视化描述 栈(stack) var a = 10; function bar(x) { var b = 5; fn(x + b); ...
- JavaScript 异步和单线程
JavaScript语言本身是单线程的,所以它自身不可能是异步.所谓单线程,就必然意味着:所有任务需要排队,前一个任务结束,才会执行后一个任务. 但js的宿主环境(比如浏览器,Node)是多线程的.宿 ...
- 【JavaScript】要点知识的个人总结(1)
米娜桑,哦哈哟~ 该篇章主要基于链接中的参考内容和代码测试得出的结论,面向具有一定基础的前端开发者.如有错误,请指出与包涵. 原型链的解释 https://juejin.im/post/5aa78fe ...
- js的单线程和异步
前言 说到js的单线程(single threaded)和异步(asynchronous),很多同学不禁会想,这不是自相矛盾么?其实,单线程和异步确实不能同时成为一个语言的特性.js选择了成为单线程的 ...
- 【 js 基础 】【 源码学习 】 setTimeout(fn, 0) 的作用
在 zepto 源码中,$.fn 对象 有个 ready 函数,其中有这样一句 setTimeout(fn,0); $.fn = { ready: function(callback){ // don ...
随机推荐
- CUBRID学习笔记 34 net参数化查询 cubrid教程示例
using CUBRID.Data.CUBRIDClient; namespace ParameterExample { class Program { static void Main(string ...
- 通知(NSNotificationCenter)
// 监听加载更多的通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoreDeals ...
- [转]产品需求文档(PRD)的写作
产品需求对产品研发而言非常重要,写不好需求,后面的一切工作流程与活动都会受到影响.转载一篇文章,关于产品需求文档写作方面的,如下: 本文摘自(一个挺棒的医学方面专家):http://www.cnblo ...
- FLASH CC 2015 CANVAS 实际应用过程中遇到的【粉色】问题(不定期更新)
1,导入音乐导致发布卡死 一开始以为是不支持,FQ搜索了一些帖子,也有说不能再时间轴加音乐,需要用代码加入,想想不太可能啊,如果真的不能为什么IDE不禁用呢? 而实际问题是: 我使用的其中一条音效有问 ...
- ctDNA 相关网站-liquid-biopsy
http://www.gene-quantification.de/liquid-biopsy.html Liquid Biopsy -- Definitions Liquid Biopsy -- r ...
- read 隐藏用户输入
有时会需要脚本用户进行输入,但不希望输入的数据显示在监视器上,典型的例子就是输入密码,当然还有很多其它类型的数据需要隐藏.-s选项就能够使read命令中输入的数据不现实在监视器上(实际上,数据是显示的 ...
- 简单的php性能注意点
什么情况,可能遇到性能问题: 1.php语法使用的不恰当 2.使用php语言做了它不擅长做的事 3.用php语言连接的服务不给力 4.php自身的短板 5.我也不知道的问题 一般情况:php性能问题不 ...
- 关于mysql的基础知识
一.数据库的简介 什么是数据库? 数据的仓库,如:在atm的实例中我们创建一个db目录称之为数据库 什么是 MySQL.Oracle.SQLite.Access.MS SQL Server等 ? 他们 ...
- golang 定时器
上网查了下相关资料,基本上都介绍的是github.com\robfig\cron这个包来执行定时任务,试了下确实可以执行.但是此包下没有删 除任务的方法,只有暂停的方法(Stop),若要停止之前的任务 ...
- wampserver2.5安装 redis缓存,igbinary, phalcon框架
wampserver2.5安装 redis缓存,igbinary, phalcon框架 根据phalconphp说明文件,先将dll文件拖入到:安装盘:\wamp\bin\php\php5.5.12\ ...