JavaScript

Deferring Execution in JavaScript

For people who use Angular, calling $timeout(fn) without a second parameter is a very familiar way of deferring execution.

But what about in plain JavaScript?

 

FIRST. setTimeout()

In much the same way, the good old setTimeout(fn) without a second parameter works just like it–deferring execution to the end of the queue.

console.log(1)
setTimeout(() => console.log(3)); 
console.log(2)

Here, the order of execution will be 1 -> 2 -> 3.

 

SECOND. Promise

There’s also creating a Promise and resolving it immediately. Even though our promise is resolved right away, it will still be pushed down the line until everyone else is done with their round of work:

console.log(1)
new Promise(resolve => resolve()).then(() => console.log(3));
console.log(2)

Again, 1 -> 2 -> 3.

 

THIRD. Async & Await

And of course, the new fancy way of writing promises in ES7.

console.log(1);
(async function() {
 await true;
 console.log(3);
})();
console.log(2);

 

END

Sometimes it can feel too hacky and awful to use double empty-timeouts to defer things a second time. For instance, in the case of waiting for elements to load before we can manually focus in on an input [1, 2].

Happy evil mixing and matching! 😀

Standard