Reputation: 539
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:
thanks
Upvotes: 3
Views: 9234
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
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
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