user582485
user582485

Reputation: 539

settimeout = setinterval with delay?

Quick question regarding settimeout, does it execute periodically like setinterval?

Say I have a line that goes like setTimeout("functionx();" , 1000) , is functionx() executed only once (after 1 second)? or does it go like this:

  1. 1 sec delay
  2. run functionx()
  3. execute functionx every 1 second after that?

thanks

Upvotes: 3

Views: 9234

Answers (3)

user657496
user657496

Reputation:

setTimeout will execute the given function after the given milliseconds. setInterval will execute the given function every given milliseconds. If you want setTimeout to act like setInterval, you'll have to make the function you specified recursive.

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401022

With setTimeout(), the function will be executed only once, after the specified delay.

That single execution is precisely the difference with setInterval(), which calls the function repeatedly.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074475

setTimeout is a one-off, the function you give it is called only once.

(Off-topic: Note that you almost never want to give either setTimeout or setInterval a string containing code; instead, give it an actual function reference.)

So this will call the function foo once, after half a second or so (these things are not precise):

function foo() {
    display("Hi there");
}
setTimeout(foo, 500);

...whereas this will keep calling it every half second or so until you stop it:

var timer = setInterval(foo, 500);
// Somewhere else, stop it:
clearInterval(timer);

Upvotes: 6

Related Questions