irt.org Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt

Q1109 What are the differences between setTimeout and setInterval, and where would the use of one would be preferable to the other?

You are here: irt.org | FAQ | JavaScript | Timeout | Q1109 [ previous next ]

<script language="JavaScript"><!--
TId = setTimeout(statement,milisecond_to_wait)  (JavaScript 1.0 =. Netscape Navigator 2+ Internet Explorer 3+)
//--></script>

will execute a statement once when the time has run out

<script language="JavaScript"><!--
IId = setInterval(statement,interval_in_miliseconds) (JavaScript 1.2 = Internet Explorer 4 Netscape Navigator 4)
//--></script>

will execute the statement every interval miliseconds.

Both can be cancelled - clearTimeout(TId) and clearInterval(IId).

I would use setTimeout and reuse it in a function to simulate setInterval:

<script language="JavaScript"><!--
function everySecond() {
   // something to do
   setTimeout('everySecond()',1000);
}

everySecond(); // start the funtion
//--></script>

©2013 Martin Webb

ArticlesFAQsGamesFeedback

FOLDOCRFCsInstant JavaScriptSoftwareBooksJavaScript Programmer's ReferenceAboutTop