What is a simple example of an asynchronous javascript function? [closed]

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):

window.setTimeout(function() {
    console.log("World");
}, 1000);
console.log("Hello");

Update: Since ES6 there are promises as an asynchronous primitive built into plain JavaScript, so you can do

 Promise.resolve("World").then(console.log); // then callbacks are always asynchronous
 console.log("Hello");

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.

Leave a Comment