ILIAS ILIAS - 2 months ago 7
Javascript Question

Animations under single threaded JavaScript

JavaScript is a single threaded language and therefore it executes one command at a time. Asynchronous programming is being implemented via Web APIs (DOM for event handling, XMLHttpRequest for AJAX calls, WindowTimers for setTimeout) and the Event queue which are managed by the browser. So far, so good! Consider now, the following very simple code:

console.log('Previous command has not yet terminated!');

Could someone please explain to me the underlying mechanism of the above? Since .hide() has not yet finished (the animation lasts 17 seconds) and JS engine is dealing with it and it is capable of executing one command at a time, in which way does it go to the next line and continues to run the remaining code?

If your answer is that animation creates promises, the question remains the same: How JavaScript is dealing with more than one thing at the same time (executing the animation itself, watching the animation queue in case of promises and proceeding with the code that follows...).

Moreover, I cannot explain how promises in jQuery work if they have to watch their parent Deferred object till it is resolved or rejected that means code execution and at the same time the remaining code is executed. How is that possible in a single threaded approach? I have no problem to understand AJAX calls for I know they are taken away from JS engine...


tl;dr; it would not be possible in a strictly single threaded environment without outside help.

I think I understand your issue. Let's get a few things out of the way:

JavaScript is always synchronous

No asynchronous APIs are defined in the language specification. All the functions like or String.fromCharCode always run synchronously*.

Code will always run to completion. Code does not stop running until it is terminated by a return, an implicit return (reaching the end of the code) or a throw (abruptly).

d(); // the order of these functions executed is always a, b, c, d and nothing else will 
     // happen until all of them finish executing

JavaScript lives inside a platform

The JavaScript language defines a concept called a host environment:

In this way, the existing system is said to provide a host environment of objects and facilities, which completes the capabilities of the scripting language.

The host environment in which JavaScript is run in the browser is called the DOM or document object model. It specifies how your browser window interacts with the JavaScript language. In NodeJS for example the host environment is entirely different.

While all JavaScript objects and functions run synchronously to completion - the host environment may expose functions of its own which are not necessarily defined in JavaScript. They do not have the same restrictions standard JavaScript code has and may define different behaviors - for example the result of document.getElementsByClassName is a live DOM NodeList which has very different behavior from your ordinary JavaScript code:

var els = document.getElementsByClassName("foo"); 
var n = document.createElement("div");
n.className = "foo";
els.length; // this increased in 1, it keeps track of the elements on the page
            // it behaves differently from a JavaScript array for example. 

Some of these host functions have to perform I/O operations like schedule timers, perform network requests or perform file access. These APIs like all the other APIs have to run to completion. These APIs are by the host platform - they invoke capabilities your code doesn't have - typically (but not necessarily) they're written in C++ and use threading and operating system facilities for running things concurrently and in parallel. This concurrency can be just background work (like scheduling a timer) or actual parallelism (like WebWorkers - again part of the DOM and not JavaScript).

So, when you invoke actions on the DOM like setTimeout, or applying a class that causes CSS animation it is not bound to the same requirements your code has. It can use threading or operating system async io.

When you do something like:

setTimeout(function() {

What actually happens is:

  • The host function setTimeout is called with a parameter of type function. It pushes the function into a queue in the host environment.
  • the console.log("Hello") is executed synchronously.
  • All other synchronous code is run (note, the setTimeout call was completely synchronous here).
  • JavaScript finished running - control is transferred to the host environment.
  • The host environment notices it has something in the timers queue and enough time has passed so it calls its argument (the function) - console.log("World") is executed.
  • All other code in the function is run synchronously.
  • Control is yielded back to the host environment (platform).
  • Something else happens in the host environment (mouse click, AJAX request returning, timer firing). The host environment calls the handler the user passed to these actions.
  • Again all JavaScript is run synchronously.
  • And so on and so on...

Your specific case

console.log('Previous command has not yet terminated!');

Here the code is run synchronously. The previous command has terminated, but it did not actually do much - instead it scheduled a callback on the platform a(in the .hide(17000) and then executed the console.log since again - all JavaScirpt code runs synchronously always.

That is - hide performs very little work and runs for a few milliseconds and then schedules more work to be done later. It does not run for 17 seconds.

Now the implementation of hide looks something like:

function hide(element, howLong) {
    var o = 16 / howLong; // calculate how much opacity to reduce each time
    //  ask the host environment to call us every 16ms
    var t = setInterval(function
        // make the element a little more transparent = (parseInt( || 1) - o;
        if(parseInt( < o) { // last step
           clearInterval(t); // ask the platform to stop calling us
  = "none"; // mark the element as hidden

So basically our code is single threaded - it asks the platform to call it 60 times a second and makes the element a little less visible each time. Everything is always run to completion but except for the first code execution the platform code (the host environment) is calling our code except for vice versa.

So the actual straightforward answer to your question is that the timing of the computation is "taken away" from your code much like in when you make an AJAX request. To answer it directly:

It would not be possible in a single threaded environment without help from outside.

That outside is the enclosing system that uses either threads or operating system asynchronous facilities - our host environment. It could not be done without it in pure standard ECMAScript.

* With the ES2015 inclusion of promises, the language delegates tasks back to the platform (host environment) - but that's an exception.