I am really struggling here to get to grips with writing asynchronous JavaScript. Could you please provide an example of a simple JavaScript function which is asynchronous written in plain JavaScript (and not using Node.js or JQuery)
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
This is asynchronous:
2 will be written to the console before 1. Because setTimeout is async.
Here's one very simple example:
You might expect these
console.log()
calls to show you0, 1, 2
etc., as in this snippet:But in fact only
10
s will be printed! The reason that functions passed intosetTimeout
function (as its 'callback' argument) will be invoked afterfor
loop is completed - i.e., afteri
value is set to 10.Yet you should understood one thing: all JavaScript in a browser executes on a single thread; asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution queue. Here's a brilliant article written by John Resig on this topic.
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.
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.An example using
setTimeout
(provided by the HTML Timing API):Update: Since ES6 there are promises as an asynchronous primitive built into plain JavaScript, so you can do
However, on their own they're not really helpful when there is nothing you could wait for (such as a timeout). And they don't change anything about the threading model either, all execution is run-to-completion without any events interfering midway.