In JavaScript, you have two options to execute a specific function in the future, i.e. after a specified time interval:

window.setInterval and window.setTimeout

 

Both functions have similar signatures, e.g.:

 

var timeout = window.setTimeout("javascript statement", milliseconds)

var intervalId = window.setInterval("code", milliseconds[, "lang"])

 

As you can see, the first difference is that the setInterval function supports running client-side script in languages other than JavaScript.  However, there is a bigger difference between the two, not discernable by syntax: the setTimeout method is completed after the function is invoked, whereas the setInterval will continue calling the specified function until clearInterval() is called or the window is closed.

 

In other words, the following two code snippets result in same outcome:

 

var t = setTimeout("refresh()", 5000);

 

function refresh()

{

    . . .

    var t = setTimeout("refresh()", 5000);

}

 

 

vs.

 

 

var i = setInterval("refresh()", 5000);

 

function refresh()

{

    . . .

}

 

 

Note: to cancel the setTimeout method, call clearTimeout.

 

 

Summary:

So, it appears clear – use setTimeout when you need to trigger a delayed function invocation once, use setInterval for multiple (timer-like) calls… 

 

There is one exception: if you need to change the parameter values passed into the function, and the data values are set (changed) during the current execution cycle, reconsider the use of setTimeout – it may remove the need for global variables, and, perhaps, be a better choice…