Whats the difference between setInterval and setTimeout?

0
127
Asked By Keven Krok On

In standard Javascript the setInterval and setTimeout functions appear to do the same thing and accept the same arguments. What is the difference between the 2 of them? When should one be used over the other?

1 Answer

Answered By Dan On

They are almost the exact same thing bar one small but very significant difference. Both methods accept a time and a function to perform when the time is run. If you use setTimeout it will run once and be done. With setInterval it will run again and again. Mixing this up can be dangerous on a website that gets a lot of traffic as it could hurt your websites performance or it could bring the users page to a crawl. Always default to using setTimeout to keep it safe.

setTimeout = runs once when the time span provided is reached

setInterval = runs over and over based on the time span provided.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.