--- title: Choosing the right approach slug: Learn/JavaScript/Asynchronous/Choosing_the_right_approach tags: - Beginner - Intervals - JavaScript - Learn - Optimize - Promises - async - asynchronous - await - requestAnimationFrame - setInterval - setTimeout - timeouts ---
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. |
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.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | Yes (recursive callbacks) | Yes (nested callbacks) | No |
An example that loads a resource via the XMLHttpRequest API (run it
live, and see
the source):
.catch() block to handle the errors for the entire chain.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.
setTimeout() is a
method that allows you to run a function after an arbitrary amount of time has passed.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| Yes | Yes (recursive timeouts) | Yes (nested timeouts) | No |
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):
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">let myGreeting = setTimeout(function() { alert('Hello, Mr. Universe!'); }, 2000)You can use recursive setTimeout() calls to run a function repeatedly in a similar fashion to setInterval(), using code like this:
There is a difference between recursive setTimeout() and setInterval():
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.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.
{{Compat("api.WindowOrWorkerGlobalScope.setTimeout")}}
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.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | Yes | No (unless they are the same) | No |
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):
requestAnimationFrame().{{Compat("api.WindowOrWorkerGlobalScope.setInterval")}}
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.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | Yes | No (unless it is the same one) | No |
A simple animated spinner; you can find this example live on GitHub (see the source code also):
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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();requestAnimationFrame(). If you need to run your animation at a slower framerate, you'll need to use setInterval() or recursive setTimeout().{{Compat("api.Window.requestAnimationFrame")}}
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.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | No | Yes | See Promise.all(), below |
The following code fetches an image from the server and displays it inside an {{htmlelement("img")}} element; see it live also, and see also the source code:
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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); });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:
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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:
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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:
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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.
{{Compat("javascript.builtins.Promise")}}
A JavaScript feature that allows you to wait for multiple promises to complete before then running a further operation based on the results of all the other promises.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | No | No | Yes |
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:
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. {{Compat("javascript.builtins.Promise.all")}}
Syntactic sugar built on top of promises that allows you to run asynchronous operations using syntax that's more like writing synchronous callback code.
| Single delayed operation | Repeating operation | Multiple sequential operations | Multiple simultaneous operations |
|---|---|---|---|
| No | No | Yes | Yes (in combination with Promise.all()) |
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):
pre data-role="codeBlock" data-info="js" class="language-javascript" class="brush: js notranslate">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();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.{{Compat("javascript.statements.async_function")}}
{{PreviousMenu("Learn/JavaScript/Asynchronous/Async_await", "Learn/JavaScript/Asynchronous")}}