But my page crashes everytime? Why?
Because the counter is only incremented inside the callback - the loop probably tries to run thousands (if not tens of thousands) of times in that time and quickly runs the browser out of memory. More accurately, as is pointed out in comments, the loop never gives up control to the setTimeout call - so that is never going to get run (Dont worry too much about the distinction here - just accept that your counter is not being incremented)
Whats the best way to add a delay of 2000ms between the alerts
Kick off the next one only as the previous one finishes.
function showHello(i){
if(i<5){
setTimeout
(
function()
{
alert("hello");
showHello(i+1)
},
2000
);
}
}
showHello(0);
Related: Is it possible to chain setTimeout functions in Javascript? and how to make a setInterval stop after some time or after a number of actions?