Link to home
Create AccountLog in
Avatar of nerdmike

asked on

Javascript: invoke function at intervals

I'm trying to figure out a way to run some Javascript code on a timer that is based inside an html document.

The first thing I thought of was to loop around a sleep function, but this doesn't seem like the best way to do it.

Ideally I could use some timer function that invokes a callback at a specified intervals like Java's Timer class.
Avatar of Zvonko
Flag of North Macedonia image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
assuming you want to call your function named foo every 3 seconds, you would just say:
Notice that the second argument is in milliseconds.
Avatar of itjstagame

setInterval is what you want, alternatively setTimeout('function()',3000); calls the function() only once not at a set interval forever like setInterval does.

But you can call a new setTimeout at the end of function().  It's not as clean but I've done this before when I wanted to change which function was being called based on certain parameters at the time, etc.
You could also use setInterval/setTimeout with anonymous functions if you want to pass some arguments, or/and easily call multiple functions.

Like this:
setInterval( function(e){
    callMethod1( arg1, arg2 );
    callMethod2( arg1, arg2 );
    callMethodWithTimerEvent( e );
}, 1000 );

This will call all three functions each second with the specified arguments.