There are times when you don't want a piece of code to run straight away but instead want to wait a while before running the code. setTimeout allows you to specify a function that is to be run after a delay of a specific number of milliseconds.
So why would you want a delay? well there are a number of reasons with the main use being for animation effects.
You can even allow for changing your mind about running the function in between running the setTimeout and when the function actually starts by assigning the value returned from the setTimeout to a variable and then passing that variable into clearTimeout so as to cancel the function's execution before it starts.
A common mistake in using this function is to pass in a string as the first parameter. The function actually takes a function as the first parameter and so when you do make that mistake the browser has to first convert the string to a function before it can run the setTimeout. It is far more efficient if you do the conversion yourself and pass in a function.
Another not so common use for setTimeout is where you want to delete an elelement from your web page from within JavaScript that is attached to that element where deleting the element will belete the script you are trying to run while you are still trying to run it. A five millisecond delay in removing the node with id="searchbox" is more than sufficient for the following code run from an event handler attached to an element within that node is sufficient time for the setTimeout to finish running before the removeChild deletes the script. This code hides the element from the page first so that it effectively disappears immediately even though there is that delay before it is actually deleted.
var s;
s = document.getElementById('searchbox');
setTimeout(function() {document.getElementsByTagName('body')[0].removeChild(s);},5);
