JavaScript:浏览器支持 vs 纯语言支持:setTimeout、setInterval

标签 javascript node.js settimeout v8

JavaScript 只是一种语言,其实现之一是 V8 引擎。它在 chrome 和 node.js 中都有使用。

DOM 支持不是 JavaScript 语言特性,它是浏览器特性(纯 JS 中没有 DOM)。同样,XMLHttpRequest 不是 JavaScript 的一部分。它是 JS 语言的浏览器插件。

我的问题Philip Roberts' JS conf EU有关谈谈他所说的,除其他外,setTimeout 不在 V8 中。我认为他可能是错的,但我不确定,这是我的问题。

当我打开 node.js(基于 V8)控制台并键入以下内容时:

> Promise
[Function: Promise]
> setTimeout
[Function]
> setInterval
[Function]
> XMLHttpRequest
ReferenceError: XMLHttpRequest is not defined
    at repl:1:1
    at REPLServer.defaultEval (repl.js:262:27)
    at bound (domain.js:287:14)
    at REPLServer.runBound [as eval] (domain.js:300:12)
    at REPLServer.<anonymous> (repl.js:431:12)
    at emitOne (events.js:82:20)
    at REPLServer.emit (events.js:169:7)
    at REPLServer.Interface._onLine (readline.js:211:10)
    at REPLServer.Interface._line (readline.js:550:8)
    at REPLServer.Interface._ttyWrite (readline.js:827:14)

我看到了:

  • Promise 原型(prototype)在那里,因为它是 ES6 的一部分,已经在新版本的 Node 下可用。它是JS作为一种语言
  • 的一部分
  • XMLHttpRequest 不存在,因为它只在浏览器中可用,它不是语言的一部分
  • setTimeoutsetInterval 都在那里。 Philip Roberts 说它们不是 - 但我看到它们在 node.js 下可用并且 我认为它们应该是,因为 setTimeout/setInterval 在单线程中有意义/异步环境,无论是浏览器还是服务器

我猜他知道他在说什么,但我想明白为什么:)


编辑:

我看到 setTimeoutwindow 对象上的一个函数。基本上,window 是非标准的东西。

最佳答案

他是对的,因为它们不是 V8 的一部分。然而,它们part of node.js (通过默认包含的模块),并以与浏览器规范兼容的方式设计:

The timer module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to call require('timers') to use the API.

The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.

关于JavaScript:浏览器支持 vs 纯语言支持:setTimeout、setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529515/

相关文章:

javascript - Owl Carousel 2获取可见元素

javascript - 根据文本更改背景

javascript - 堆叠可选 promise 的正确方法

node.js - 在ubuntu 14.04上执行dockerode npm的以下代码后出现错误 "connect EACCES/var/run/docker.sock"

javascript - setTimeout 和clearTimeout 问题

javascript - 清除特定输入字段的范围文本

javascript - 如何在javascript中引用目录

node.js - Sequelize如何返回被破坏的行

javascript - 延迟为1调用setTimeout的目的是什么?

javascript - 为什么使用setTimeout函数会立即执行?