Choosing the right approach

このロケールの翻訳が存在しないため、英語バージョンのコンテンツを表示しています。 Help us translate this article!

To finish this module off, we'll provide a brief discussion of the different coding techniques and features we've discussed throughout, looking at which one you should use when, with recommendations and reminders of common pitfalls where appropriate. We'll probably add to this resource as time goes on.

Prerequisites: Basic computer literacy, a reasonable understanding of JavaScript fundamentals.
Objective: To be able to make a sound choice of when to use different asynchronous programming techniques.

Asynchronous callbacks

Generally found in old-style APIs, involves a function being passed into another function as a parameter, which is then invoked when an asynchronous operation has been completed, so that the callback can in turn do something with the result. This is the precursor to promises; it's not as efficient or flexible. Use only when necessary.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No Yes (recursive callbacks) Yes (nested callbacks) No

Code example

An example that loads a resource via the XMLHttpRequest API (run it live, and see the source):

function loadAsset(url, type, callback) {
  let xhr = new XMLHttpRequest();
  xhr.open('GET', url);
  xhr.responseType = type;

  xhr.onload = function() {
    callback(xhr.response);
  };

  xhr.send();
}

function displayImage(blob) {
  let objectURL = URL.createObjectURL(blob);

  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}

loadAsset('coffee.jpg', 'blob', displayImage);

Pitfalls

  • Nested callbacks can be cumbersome and hard to read (i.e. "callback hell").
  • Failure callbacks need to be called once for each level of nesting, whereas with promises you can just use a single .catch() block to handle the errors for the entire chain.
  • Async callbacks just aren't very graceful.
  • Promise callbacks are always called in the strict order they are placed in the event queue; async callbacks aren't.
  • Async callbacks lose full control of how the function will be executed when passed to a third-party library.

Browser compatibility

Really good general support, although the exact support for callbacks in APIs depends on the particular API. Refer to the reference documentation for the API you're using for more specific support info.

Further information

setTimeout()

setTimeout() is a method that allows you to run a function after an arbitrary amount of time has passed.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
Yes Yes (recursive timeouts) Yes (nested timeouts) No

Code example

Here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code):

let myGreeting = setTimeout(function() {
  alert('Hello, Mr. Universe!');
}, 2000)

Pitfalls

You can use recursive setTimeout() calls to run a function repeatedly in a similar fashion to setInterval(), using code like this:

let i = 1;
setTimeout(function run() {
  console.log(i);
  i++;

  setTimeout(run, 100);
}, 100);

There is a difference between recursive setTimeout() and setInterval():

  • Recursive setTimeout() guarantees at least the specified amount of time (100ms in this example) will elapse between the executions; the code will run and then wait 100 milliseconds before it runs again. The interval will be the same regardless of how long the code takes to run.
  • With setInterval(), the interval we choose includes the time taken to execute the code we want to run in. Let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds.

When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get errors.

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
setTimeoutChrome Full support 30Edge Full support YesFirefox Full support 1
Full support 1
Full support 52
Notes
Notes setInterval now defined on WindowOrWorkerGlobalScope mixin.
IE Full support 4Opera Full support 4Safari Full support 1WebView Android Full support YesChrome Android Full support 30Firefox Android Full support 4
Full support 4
Full support 52
Notes
Notes setInterval now defined on WindowOrWorkerGlobalScope mixin.
Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android ?
Supports parameters for callbackChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support 10Opera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android ?
Throttling of tracking timeout scriptsChrome ? Edge ? Firefox Full support 55IE ? Opera ? Safari ? WebView Android ? Chrome Android ? Firefox Android Full support 55Opera Android ? Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

Further information

setInterval()

setInterval() is a method that allows you to run a function repeatedly with a set interval of time between each execution. Not as efficient as requestAnimationFrame(), but allows you to choose a running rate/frame rate.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No Yes No (unless it is the same one) No

Code example

The following function creates a new Date() object, extracts a time string out of it using toLocaleTimeString(), and then displays it in the UI. We then run it once per second using setInterval(), creating the effect of a digital clock that updates once per second (see this live, and also see the source):

function displayTime() {
   let date = new Date();
   let time = date.toLocaleTimeString();
   document.getElementById('demo').textContent = time;
}

const createClock = setInterval(displayTime, 1000);

Pitfalls

  • The frame rate isn't optimized for the system the animation is running on, and can be somewhat inefficient. Unless you need to choose a specific (slower) framerate, it is generally better to use requestAnimationFrame().

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
setIntervalChrome Full support 30Edge Full support YesFirefox Full support 1
Full support 1
Full support 52
Notes
Notes setInterval now defined on WindowOrWorkerGlobalScope mixin.
IE Full support 4Opera Full support 4Safari Full support 1WebView Android Full support YesChrome Android Full support 30Firefox Android Full support 4
Full support 4
Full support 52
Notes
Notes setInterval now defined on WindowOrWorkerGlobalScope mixin.
Opera Android Full support 10.1Safari iOS Full support 1Samsung Internet Android ?
Supports parameters for callbackChrome Full support YesEdge Full support YesFirefox Full support YesIE Full support 10Opera Full support YesSafari ? WebView Android Full support YesChrome Android Full support YesFirefox Android ? Opera Android ? Safari iOS ? Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

Further information

requestAnimationFrame()

requestAnimationFrame() is a method that allows you to run a function repeatedly, and efficiently, at the best framerate available given the current browser/system. You should, if at all possible, use this instead of setInterval()/recursive setTimeout(), unless you need a specific framerate.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No Yes No (unless it is the same one) No

Code example

A simple animated spinner; you can find this example live on GitHub (see the source code also):

const spinner = document.querySelector('div');
let rotateCount = 0;
let startTime = null;
let rAF;

function draw(timestamp) {
    if(!startTime) {
        startTime = timestamp;
    }

    rotateCount = (timestamp - startTime) / 3;

    if(rotateCount > 359) {
        rotateCount %= 360;
    }

    spinner.style.transform = 'rotate(' + rotateCount + 'deg)';

    rAF = requestAnimationFrame(draw);
}

draw();

Pitfalls

  • You can't choose a specific framerate with requestAnimationFrame(). If you need to run your animation at a slower framerate, you'll need to use setInterval() or recursive setTimeout().

Browser compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
requestAnimationFrameChrome Full support 24
Full support 24
Full support 10
Prefixed
Prefixed Implemented with the vendor prefix: webkit
Edge Full support 12Firefox Full support 23
Notes
Full support 23
Notes
Notes Callback parameter is a DOMHighResTimestamp. This means ten microsecond precision and zero time as performance.now().
No support 11 — 42
Prefixed Notes
Prefixed Implemented with the vendor prefix: moz
Notes Callback parameter is a DOMTimestamp. This means millisecond precision and zero time as Date.now().
No support 4 — 11
Prefixed Notes
Prefixed Implemented with the vendor prefix: moz
Notes Could be called with no input parameters.
IE Full support 10Opera Full support 15
Full support 15
No support ? — 15
Prefixed
Prefixed Implemented with the vendor prefix: o
Safari Full support 6.1
Full support 6.1
Full support 6
Prefixed
Prefixed Implemented with the vendor prefix: webkit
WebView Android Full support YesChrome Android Full support 25
Full support 25
Full support 18
Prefixed
Prefixed Implemented with the vendor prefix: webkit
Firefox Android Full support 23
Full support 23
No support 14 — 42
Prefixed
Prefixed Implemented with the vendor prefix: moz
Opera Android Full support 14
Full support 14
No support ? — 14
Prefixed
Prefixed Implemented with the vendor prefix: o
Safari iOS Full support 7
Full support 7
Full support 6.1
Prefixed
Prefixed Implemented with the vendor prefix: webkit
Samsung Internet Android Full support Yes
Return valueChrome Full support 23Edge Full support YesFirefox Full support 11IE Full support 10Opera Full support 15Safari Full support 6.1WebView Android Full support YesChrome Android Full support 25Firefox Android Full support 14Opera Android Full support 14Safari iOS Full support 6.1Samsung Internet Android ?

Legend

Full support  
Full support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.
Requires a vendor prefix or different name for use.
Requires a vendor prefix or different name for use.

Further information

Promises

Promises are a JavaScript feature that allows you to run asynchronous operations and wait until it is definitely complete before running another operation based on its result. Promises are the backbone of modern asynchronous JavaScript.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No No Yes See Promise.all(), below

Code example

The following code fetches an image from the server and displays it inside an <img> element; see it live also, and see also the source code:

fetch('coffee.jpg')
.then(response => response.blob())
.then(myBlob => {
  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
})
.catch(e => {
  console.log('There has been a problem with your fetch operation: ' + e.message);
});

Pitfalls

Promise chains can be complex and hard to parse. If you nest a number of promises, you can end up with similar troubles to callback hell. For example:

remotedb.allDocs({
  include_docs: true,
  attachments: true
}).then(function (result) {
  let docs = result.rows;
  docs.forEach(function(element) {
    localdb.put(element.doc).then(function(response) {
      alert("Pulled doc with id " + element.doc._id + " and added to local db.");
    }).catch(function (err) {
      if (err.name == 'conflict') {
        localdb.get(element.doc._id).then(function (resp) {
          localdb.remove(resp._id, resp._rev).then(function (resp) {
// et cetera...

It is better to use the chaining power of promises to go with a flatter, easier to parse structure:

remotedb.allDocs(...).then(function (resultOfAllDocs) {
  return localdb.put(...);
}).then(function (resultOfPut) {
  return localdb.get(...);
}).then(function (resultOfGet) {
  return localdb.put(...);
}).catch(function (err) {
  console.log(err);
});

or even:

remotedb.allDocs(...)
.then(resultOfAllDocs => {
  return localdb.put(...);
})
.then(resultOfPut => {
  return localdb.get(...);
})
.then(resultOfGet => {
  return localdb.put(...);
})
.catch(err => console.log(err));

That covers a lot of the basics. For a much more complete treatment, see the excellent We have a problem with promises, by Nolan Lawson.

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
PromiseChrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
Promise() constructorChrome Full support 32Edge Full support 12Firefox Full support 29
Notes
Full support 29
Notes
Notes Constructor requires a new operator since version 37.
IE No support NoOpera Full support 19Safari Full support 8
Notes
Full support 8
Notes
Notes Constructor requires a new operator since version 10.
WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29
Notes
Full support 29
Notes
Notes Constructor requires a new operator since version 37.
Opera Android Full support YesSafari iOS Full support 8
Notes
Full support 8
Notes
Notes Constructor requires a new operator since version 10.
Samsung Internet Android Full support 2.0nodejs Full support 0.12
Notes
Full support 0.12
Notes
Notes Constructor requires a new operator since version 4.
all()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
allSettled()Chrome Full support 76Edge No support NoFirefox Full support 71IE No support NoOpera ? Safari ? WebView Android Full support 76Chrome Android Full support 76Firefox Android No support NoOpera Android Full support YesSafari iOS ? Samsung Internet Android No support Nonodejs Full support 12.9.0
catch()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
finally()Chrome Full support 63Edge Full support 18Firefox Full support 58IE No support NoOpera Full support 50Safari Full support 11.1WebView Android Full support 63Chrome Android Full support 63Firefox Android Full support 58Opera Android Full support 46Safari iOS Full support 11.3Samsung Internet Android Full support 8.0nodejs Full support 10.0.0
prototypeChrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
race()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
reject()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
resolve()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12
then()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support
Compatibility unknown  
Compatibility unknown
See implementation notes.
See implementation notes.

Further information

Promise.all()

A JavaScript feature that allows you wait for multiple promises to complete before then running a further operation based on the results of all the other promises.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No No No Yes

Code example

The following example fetches several resources from the server, and uses Promise.all() to wait for all of them to be available before then displaying all of them — see it live, and see the source code:

function fetchAndDecode(url, type) {
  // Returning the top level promise, so the result of the entire chain is returned out of the function
  return fetch(url).then(response => {
    // Depending on what type of file is being fetched, use the relevant function to decode its contents
    if(type === 'blob') {
      return response.blob();
    } else if(type === 'text') {
      return response.text();
    }
  })
  .catch(e => {
    console.log(`There has been a problem with your fetch operation for resource "${url}": ` + e.message);
  });
}

// Call the fetchAndDecode() method to fetch the images and the text, and store their promises in variables
let coffee = fetchAndDecode('coffee.jpg', 'blob');
let tea = fetchAndDecode('tea.jpg', 'blob');
let description = fetchAndDecode('description.txt', 'text');

// Use Promise.all() to run code only when all three function calls have resolved
Promise.all([coffee, tea, description]).then(values => {
  console.log(values);
  // Store each value returned from the promises in separate variables; create object URLs from the blobs
  let objectURL1 = URL.createObjectURL(values[0]);
  let objectURL2 = URL.createObjectURL(values[1]);
  let descText = values[2];

  // Display the images in <img> elements
  let image1 = document.createElement('img');
  let image2 = document.createElement('img');
  image1.src = objectURL1;
  image2.src = objectURL2;
  document.body.appendChild(image1);
  document.body.appendChild(image2);

  // Display the text in a paragraph
  let para = document.createElement('p');
  para.textContent = descText;
  document.body.appendChild(para);
});

Pitfalls

  • If a Promise.all() rejects, then one or more of the promises you are feeding into it inside its array parameter must be rejecting, or might not be returning promises at all. You need to check each one to see what they returned. 

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
all()Chrome Full support 32Edge Full support 12Firefox Full support 29IE No support NoOpera Full support 19Safari Full support 8WebView Android Full support 4.4.3Chrome Android Full support 32Firefox Android Full support 29Opera Android Full support YesSafari iOS Full support 8Samsung Internet Android Full support 2.0nodejs Full support 0.12

Legend

Full support  
Full support
No support  
No support

Further information

Async/await

Syntactic sugar built on top of promises that allows you to run asynchronous operations using syntax that's more like writing synchronous callback code.

Useful for...
Single delayed operation Repeating operation Multiple sequential operations Multiple simultaneous operations
No No Yes Yes (in combination with Promise.all())

Code example

The following example is a refactor of the simple promise example we saw earlier that fetches and displays an image, written using async/await (see it live, and see the source code):

async function myFetch() {
  let response = await fetch('coffee.jpg');
  let myBlob = await response.blob();

  let objectURL = URL.createObjectURL(myBlob);
  let image = document.createElement('img');
  image.src = objectURL;
  document.body.appendChild(image);
}

myFetch();

Pitfalls

  • You can't use the await operator inside a non-async function, or in the top level context of your code. This can sometimes result in an extra function wrapper needing to be created, which can be slightly frustrating in some circumstances. But it is worth it most of the time.
  • Browser support for async/await is not as good as that for promises. If you want to use async/await but are concerned about older browser support, you could consider using the BabelJS library — this allows you to write your applications using the latest JavaScript and let Babel figure out what changes if any are needed for your user’s browsers.

Browser compatibility

Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
async functionChrome Full support 55Edge Full support 15Firefox Full support 52IE No support NoOpera Full support 42Safari Full support 10.1WebView Android Full support YesChrome Android Full support 55Firefox Android Full support 52Opera Android Full support 42Safari iOS Full support 10.3Samsung Internet Android Full support 6.0nodejs Full support 7.6.0
Full support 7.6.0
Full support 7.0.0
Disabled
Disabled From version 7.0.0: this feature is behind the --harmony runtime flag.

Legend

Full support  
Full support
No support  
No support
User must explicitly enable this feature.
User must explicitly enable this feature.

Further information

In this module