PDA

View Full Version : A right way to make a function constantly be called


CSSjunkie
02-12-2008, 02:04 AM
Hi first post here, so here goes

My problem is that I want to use javascript to every now and then check with the server and update, but the main part is that I'm pretty sure that the way I'm doing this isn't right, or there isn't a right way. I'm not too sure.

function foo(){

// do some stuff

setTimeout("foo()",2000);

}

is this a good way to have a function constantly be called?

j3n0vacHiLd
02-12-2008, 02:11 AM
Yep, nothing wrong with that. Just don't forget to make the initial call to that function.

CSSjunkie
02-12-2008, 02:13 AM
Cool thanks for such a quick reply

liorean
02-12-2008, 08:00 AM
function foo(){
// do some stuff
setTimeout("foo()",2000);
}is this a good way to have a function constantly be called?It's a reasonably good approach. You really shouldn't use a string with setTimeout though, you should use a function object.function foo(){
// do some stuff
setTimeout(foo,2000);
}

Another way to do it is of coursefunction foo(){
// do some stuff
}
setInterval(foo,2000);This way you don't add the processing time to the 2000ms in between calls.

CSSjunkie
02-14-2008, 03:47 AM
Cool, Thanks for showing this method. That was exactly what I was trying to achieve with setTimeout() in fact!