更新时间:2022-05-19 08:44:36
JavaScript的本身是同步的,单线程的。你不能写一个异步函数;纯JS没有时间API。届时将有来自并行线程没有副作用。
JavaScript itself is synchronous and single-threaded. You cannot write an asynchronous function; plain JS has no timing API. There will be no side-effects from parallel threads.
你可以做的是使用由环境(Node.js的,的网页浏览器),让您安排异步任务提供了一些API - 使用超时,AJAX功能,FileAPI, requestAnimationFrame
, nextTick
,WebWorkers,DOM事件,等等。
What you can do is use some APIs provided by your environment (Node.js, Webbrowser) that allow you to schedule asynchronous tasks - using timeouts, ajax, FileAPI, requestAnimationFrame
, nextTick
, WebWorkers, DOM events, whatever.
用一个例子 的setTimeout
一>(由 HTML时序API 提供):
window.setTimeout(function() {
console.log("World");
}, 1000);
console.log("Hello");