JavaScript SetInterval and setTimeout use method details

  • 2020-03-29 23:46:15
  • OfStack

SetTimeout and setInterval have the same syntax. They all take two arguments, one for the string of code to be executed, and one for the millisecond interval when the code is executed.
However, there is a difference between the two functions. SetInterval will automatically execute the code again after a fixed time interval, while setTimeout will execute that code only once.
The difference between:
Window. The setTimeout (" function ", time); // sets a timeout object to execute only once without a period
Window. The setInterval (" function ", time); // set a timeout object, period = 'interaction time'
Stop timing:
ClearTimeout (object) clears the setTimeout object that has been set
Clears the setInterval object that has been set


function PerRefresh() {
     var today = new Date();
     alert("The time is: " + today.toString());
     setTimeout("showTime()", 5000);

  Once called, PerReflesh displays the time every five seconds

setInterval("PerRefresh()", 5000);

function PerRefresh() {
     var today = new Date();
     alert("The time is: " + today.toString());

SetInterval, on the other hand, is not bound by the function it calls; it simply repeats that function at regular intervals.
As long as setInterval("PerRefresh()", 5000) is called, the PerRefresh function is executed every 5 seconds.
SetInterval is best if you want to perform an action exactly after a fixed interval, but setTimeout is best if you don't want to interfere with each other through successive calls, especially if each function call requires heavy computation and long processing time.
SetInterval executes the specified code until clearInterval is called to clear the timer object
SetTimeout executes the specified code once, using clearTimeout to clear the timer object
Both setInterval and setTimeout return the timer object identifier for the clearInterval and clearTimeout calls

Related articles: