PDA

View Full Version : Run Function every x many seconds



Snetty
Jan 19th, 2007, 04:32 PM
title says it all tbh.

I'm trying to write a script that will run a function every x many seconds. I'd have thought that there would be a function for this already, but I didnt find anything. So I wrote the following..



do{

now = new Date
seconds = now.getSeconds()

if(seconds+"2" == now.getSeconds()){

function();

}

}

while(1)


Which didn't work.. just hung the browser. BTW 2 is the interval in seconds...

Any help will be much appreciated.

matrixIII
Jan 19th, 2007, 04:42 PM
Try something like this..
Note the 1 in function call parameter.. this will call the function every 1 miniute.



<script language='Javascript'>
<!--
function timedCall()
{
alert('here');
setTimeout( "timedCall()", 1*60*1000 );
}
var timedCaller= setTimeout( "timedCall()", 1*60*1000 );
//-->
</script>

Snetty
Jan 19th, 2007, 04:56 PM
Thanks for the response... I've tried that using the following variation:



window.onload = repeatingajaxFunction('thing.php', 'arelevantid');

function repeatingajaxFunction(url, outputID){

ajaxFunction(url, outputID);
setTimeout("repeatingajaxFunction(url, outputID)", 2*1000 );

}


which doesn't work, although atleast it doesn't hang the browser this time. My debug tells me that after the first iteration, the variables aren't being passed on.

Snetty
Jan 19th, 2007, 04:57 PM
w00t.. nevermind.. removed the quotes around repeatingajaxFunction(url, outputID) and it works now!

thanks for the help

Snetty
Jan 19th, 2007, 05:06 PM
scrub that.. it sort of works, but whatever time I put in, i just ignores it and goes as quick as it can.

dumpfi
Jan 19th, 2007, 05:17 PM
Try this:

window.onload = repeatingajaxFunction('thing.php', 'arelevantid');

function repeatingajaxFunction(url, outputID)
{
ajaxFunction(url, outputID);
setTimeout(
function()
{
repeatingajaxFunction(url, outputID)
},
2000
);

}
dumpfi

Snetty
Jan 19th, 2007, 06:43 PM
nice one dumpfi.. that worked wonderfully

felgall
Jan 19th, 2007, 08:25 PM
You are doing it the long way. Simply replace setTimeout() with setInterval() and it will run multiple times by itself without any extra code needed.

window.onload = function() {setInterval(function() {ajaxFunction(('thing.php', 'arelevantid')},2000);};