转自: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 onClickonLoadonDone
  • 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:

  1. We step into the console.log('Hi'); function, so it’s pushed onto the call stack.
  2. console.log('Hi'); returns, so it’s popped off the top of the stack.
  3. We step into the setTimeout function, so it’s pushed onto the call stack.
  4. setTimeout is part of the web API, so the web API handles that and times out the 2 seconds.
  5. We continue our script, stepping into the console.log('Everybody') function, pushing it onto the stack.
  6. console.log('Everybody') returns, so it’s popped off the stack.
  7. The 2-second timeout completes, so the callback moves to the callback queue.
  8. 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.
  9. 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的更多相关文章

  1. 对javascript EventLoop事件循环机制不一样的理解

    前置知识点: 浏览器原理,浏览器内核5种线程及协作,JS引擎单线程设计推荐阅读: 从浏览器多进程到JS单线程,JS运行机制最全面的一次梳理 [FE]浏览器渲染引擎「内核」 js异步编程,Promise ...

  2. 初识JavaScript EventLoop

    Event Loop指的是计算机系统的一种运行机制.JavaScript采用此机制解决单线程引发相关问题 在浏览器中的web应用会涉及到.JavaScript引擎.WebAPI.Event Loop. ...

  3. JavaScript的sleep实现--Javascript异步编程学习

    一.原始需求 最近在做百度前端技术学院的练习题,有一个练习是要求遍历一个二叉树,并且做遍历可视化即正在遍历的节点最好颜色不同 二叉树大概长这个样子: 以前序遍历为例啊, 每次访问二叉树的节点加个sle ...

  4. JavaScript Concurrency model and Event Loop 并发模型和事件循环机制

    原文地址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop JavaScript 有一个基于 event loop 的 ...

  5. javascript运行时中的堆栈和队列

    下面是一个理论上的模型,js引擎着重实现和优化了描述的这几个语义 可视化描述 栈(stack) var a = 10; function bar(x) { var b = 5; fn(x + b); ...

  6. JavaScript 异步和单线程

    JavaScript语言本身是单线程的,所以它自身不可能是异步.所谓单线程,就必然意味着:所有任务需要排队,前一个任务结束,才会执行后一个任务. 但js的宿主环境(比如浏览器,Node)是多线程的.宿 ...

  7. 【JavaScript】要点知识的个人总结(1)

    米娜桑,哦哈哟~ 该篇章主要基于链接中的参考内容和代码测试得出的结论,面向具有一定基础的前端开发者.如有错误,请指出与包涵. 原型链的解释 https://juejin.im/post/5aa78fe ...

  8. js的单线程和异步

    前言 说到js的单线程(single threaded)和异步(asynchronous),很多同学不禁会想,这不是自相矛盾么?其实,单线程和异步确实不能同时成为一个语言的特性.js选择了成为单线程的 ...

  9. 【 js 基础 】【 源码学习 】 setTimeout(fn, 0) 的作用

    在 zepto 源码中,$.fn 对象 有个 ready 函数,其中有这样一句 setTimeout(fn,0); $.fn = { ready: function(callback){ // don ...

随机推荐

  1. CUBRID学习笔记 21 查看主键外键索引

    命令 show create table game; game是表名 在web管理中,请在sql标签中查,不要在query中执行. show create table game; === <Re ...

  2. python_way.day7 模块(configparser,xml,shutil,subprocess)、面向对象(上)(创建类,类的构成,函数式编程与面向对象编程的选择,类的继承)

      python_way.day7 1.模块 configparser,xml,shutil,subprocess 1.模块 a.configparser 用于处理特定格式的文件,其本职上使用open ...

  3. kakfa源码编译打包

    kakfa项目编译: cd /home/zhaofuxin/workspace/kafka-0.8.2.1-src ./gradlew releaseTarGz 会出现如下异常: zhaofuxin@ ...

  4. img_jquerydim

  5. Eclipse使用Jetty(转)

    eclipse 与 jetty 结合的最佳实践 http://www.cnblogs.com/mignet/archive/2011/12/04/eclipse_jetty_perfect_integ ...

  6. 解耦HTML、CSS和JavaScript

    当前在互联网上,任何一个稍微复杂的网站或者应用程序都会包含许多HTML.CSS和JavaScript.随着互联网运用的发展以及我们对它的依赖性日益增加,设定一个关于组织和维护你的前端代码的计划是绝对需 ...

  7. spring之aop概念和配置

    面向切面的一些概念: 简单说: 连接点就一些方法,在这些方法基础上需要额外的一些业务需求处理. 切入点就是方法所代表的功能点组合起来的功能需求. 通知就是那些额外的操作. 织入就是使用代理实现整个切入 ...

  8. poj2187Beauty Contest(凸包直径)

    链接 利用旋转卡壳 参考博客http://www.cppblog.com/staryjy/archive/2010/09/25/101412.html #include <iostream> ...

  9. JS重要知识点(转载 学习中。。。)

    这里列出了一些JS重要知识点(不全面,但自己感觉很重要).彻底理解并掌握这些知识点,对于每个想要深入学习JS的朋友应该都是必须的. 讲解还是以示例代码搭配注释的形式,这里做个小目录: JS代码预解析原 ...

  10. maven install 报错Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project*****

    [ERROR]Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-co ...