2

i got a problem with setTimeout.. i dont know why this will not work..

$(document).ready(function(){
var counterNum = 0;

function tick()
{        
    addText(counterNum);
    setTimeout('tick()',1000);
    counterNum++;
}

function addText(strNum)
{
 $("div.counter").empty();
 $("div.counter").append(strNum);           
}
});​

you can check it here for the live preview LINK

and also sir, what is the difference between

setTimeout('tick()',1000);

and

setTimeout(tick(),1000);

?

2 Answers 2

4

Try:

$(document).ready(function(){
var counterNum = 0;

function tick()
{        
    addText(counterNum);
    setTimeout(tick,1000);
    counterNum++;
}

function addText(strNum)
{
 $("div.counter").empty();
 $("div.counter").append(strNum+"");   

}

tick();

});

The difference between

setTimeout('tick()',1000)

and

setTimeout(tick(), 1000)

is that the second one will not wait 1000ms to execute, but if you changed it to

setTimeout(tick, 1000)

it would be effectively the same. Technically, it would change the scope of where the function was called from.

1

In the case of passing in a string JavaScript has to evaluate it to run your code. With setTimeOut you should always use a pattern like this:

var self = this;
setTimeout(function(){tick();},1000);

This gives you closure and allows you to get around the fact that using setTimeOut changes what this is to be the global object window (a nastly little surprise for developers the first time they encounter it).

Try that in combination with Fredrik recommendeds and you should be in good shape.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.