转自: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.

转载于:https://www.cnblogs.com/bonelee/p/6186369.html

JavaScript EventLoop相关推荐

  1. javascript运行机制

    阮一峰的网络日志 » 首页 » 档案 搜索 上一篇:乔布斯的管理课 下一篇:编译器的工作过程 分类: JavaScript JavaScript 运行机制详解:再谈Event Loop 作者: 阮一峰 ...

  2. 试图解释清楚【JavaScript Event Loop】

    本篇文章较长,让网络飞一会再看~ 本文结构 - 带着问题看这篇文章 - JS Runtime的几个概念 - Event Loop事件循环 - UI Rendering Task - 可视化:event ...

  3. 了解EventLoop就明白为何 js 是单线程?| 前端面试基础

    前置概念 在了解 EventLoop 事件循环 前,先铺垫一些基础概念. 堆和栈 堆和栈是计算机领域的术语: 栈(stack)又名堆栈,它是一种运算受限的线性表.限定仅在表尾进行插入和删除操作的线性表 ...

  4. 正确理解javascript中的Event loop机制

    这两个星期一直在想着写一篇关于javascript中event Loop的文章.自从写完上一篇<Javascript捕捉(capturing)与冒泡(bubbling)的区别>之后,我抛出 ...

  5. vue 刷新echarts_用Vue开发动态刷新Echarts组件(以及修改时遇到的问题)

    通过这篇文章我学习了vue集成echarts,尝试了一下demo没问题,但是在修改我预期效果时,却出了一点问题,最后解决思路见最后 从几年前流行的jQuery插件,到现在React和Vue的组件,在业 ...

  6. Angular:失焦校验和失焦方法冲突的解决方案 事件循环

    问题描述: 今天做项目中,一个input元素中同时添加了 失焦方法 和 失焦校验.今天发现偶发的会仅触发其中一个.和大佬同事讨论许久,发现可能是 二者其一 被另外一个冲掉了. 如果触发了失焦校验,那么 ...

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

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

  8. MDN Web Docs

    MDN Web Docs MDN Web Docs(MDN 网络文档,MDN即Mozilla Developer Network )是免费的资源. MDN Web Docs提供开放网络(Open We ...

  9. 整理一波国外前端学习网站

    国内的普通开发者对于掌握一门新的技术不知道从哪里下手,看哪些书.为了获得相关知识会关注各种公众号.购买各种视频课程来学习,但由于这些内容本身有碎片化的特点,效果往往不太理想.以至于付出了大量的时间到最 ...

最新文章

  1. 青龙羊毛——飞鸽花转省毛毛(搬运)
  2. mysql当前用户user()与current_user()
  3. vue-video-player集成videojs-contrib-hls实现.m3u8文件播放
  4. python实现e2lsh高维数据集k近邻搜索——实现流程
  5. UtilSession failed: Prerequisite check CheckSystemSpace space(22288172004) is not availa
  6. 计算机硬件外围设备介绍,天津2012年自考“计算机外围设备使用与维护”课程考试大纲...
  7. pointer-events(禁止鼠标事件)
  8. c++rpg黑框游戏_c++实现简单RPG对战游戏的代码
  9. parquet格式_数据工程101:揭开Hadoop数据格式的神秘面纱:Avro,ORC和Parquet
  10. 农行笔试编程题(Java)记录
  11. BT中的磁力链接(转)
  12. 计算机二级vb题库公众号,计算机二级vb题库
  13. 免费PPT模板下载??
  14. 八孔g调短洞箫_八孔G调的箫,对应的1234567应该分别按哪些孔?
  15. 小心利用大家的爱国热情来传播Worm.Win32.AutoRun.dgk的网页
  16. 【MySQL基本查询】Create(创建), Retrieve(读取),Update(更新),Delete(删除)
  17. Excel如何从混合数据中提取出手机号码
  18. python连接MySQL数据库的示例代码
  19. 彻底关闭win10自动更新(针对已经关闭windows update项,但系统仍自动更新的问题)
  20. 【前端小点】CSS之background背景属性详解

热门文章

  1. ubuntu samba重启 mount命令
  2. mysql 查询结果行变列_SQL 查询怎么将行变成列
  3. python实现logistic_用Python实现机器学习算法—Logistic 回归算法
  4. 电脑卡顿不流畅是什么原因_为什么Windows/iOS操作很流畅,而Linux/Android却很卡顿呢...
  5. vue实现一个星级打分效果_五分钟用vue实现一个五星打分效果
  6. 计算机与十进制 教案,二进制与十进制间的转换教案
  7. php video标签使用方法,HTML_HTML5 video标签(播放器)学习笔记(一):使用入门,近有在学习html5中video标签(播 - phpStudy...
  8. mysql的模糊查询以及时间类型整理
  9. 【响应式Web前端设计】css如何设置边框的圆角样式?border-radius属性设置圆角样式(图 文)
  10. Android四种启动模式