Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (7k points)

These two pieces of code behave the sameway:

Code 1:

function myTimeoutFunction()

{

    doStuff();

    setTimeout(myTimeoutFunction, 1000);

}

myTimeoutFunction();

Code 2:

function myTimeoutFunction()

{

    doStuff();

}

myTimeoutFunction();

setInterval(myTimeoutFunction, 1000);

Is there any difference between using setTimeout and setInterval?

1 Answer

0 votes
by (13.1k points)

They both essentially try to do the same thing, but the setInterval approach is more accurate than the setTimeout function, since the setTimeout function waits 1000ms, it runs the function and sets another timeout this would make the waiting period more than 1000ms.

Though you might think that setInterval is going to execute exactly every 1000ms, it is important to note that setInterval will also delay as Javascript is not a multithreaded language, which means that if there are other parts of the script running then the interval will have to wait for that to finish.

If your programming something precise that does not need these delays, you should go for a self-adjusting timer.

Want to be a full stack developer? Check out the full stack developer course from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...