← home← blog

setTimeout - a temporary hack

29 Jan 2013

The JavaScript below is perfectly legal, it grabs a DOM element that doesn't exist and then sets it's text. No errors at all.

setTimeout(function () {
    document.getElementById('myEl').innerText = 'Hey there, yo!';
}, 0);

var myDiv = document.createElement('div');
myDiv.id = 'myEl';
document.body.appendChild(myDiv);

Great Odin's raven!?

Imagine your code as building blocks, all stacked on top of each other, this is how the browser's engine executes your JavaScript - top to bottom. It processes one piece then the next, then the next, one at a time, essentially blocking the progress of execution until the current operation is complete. JavaScript is single-threaded, ie. it can't do more than one thing at a time, like a multi-threaded application can. What's actually happening above is that the setTimeout is added to the browsers event queue, right at the end. So it's not executed until all other operations in the current stack are carried out and complete.

tl;dr

setTimeout() buys you some time until the DOM elements are loaded (and rendering is complete), even if it's set to 0.

Deeper understanding

Resig's How JavaScript Timers Work

I'm available for hire

Hire me