牛さん
牛さん

Reputation: 3006

How many times on earth does setTimeout execute?

I know this may be an old question. But I'm really confused after a few googling.

From this question, I learn the setTimeout will execute forever,

but from this one, I learn it will execute only once.

What's strange is that when I test it in browser console, I happen to see it keeps executing..

enter image description here

But sometimes it only execute once:

enter image description here

The same code gives different result. Anyone know why?

EDITED: I now can believe setTimeout executes only once, but how to explain the first screenshot of my test?

Upvotes: 1

Views: 2143

Answers (2)

kahowell
kahowell

Reputation: 30156

setTimeout does not execute forever, though as demonstrated in the linked question, you can emulate setInterval by calling setTimeout again in the function you pass to setTimeout

This answer explains that the return value from setTimeout/setInterval is one that you can use to refer to the timer later to cancel the timeout.

Upvotes: 1

Coin_op
Coin_op

Reputation: 10718

setTimeout will only execute once.

The code in the stackoverflow question you linked to keeps executing because it is recursive. The setTimeout call, calls itself.

Upvotes: 5

Related Questions