setTimeout vs. setInterval
von Andreas Möller
setTimeout and setInterval are to two Javscript core functions which can call any custom function periodically in a asynchronous manner. But what is the difference between them? This article presents a comparsion of the functions by studying the output of a test program. The test program uses the function workload from listing 1 to produce workload by calling n-times a product of four random numbers, line 3.
Line 1 of listing 2 initalizes the variable start by the absolute start time of the test program. The runtime of workload, listinig 1, is measured and loged by the wrapper function logWorkload, line 3-8. Within logWorkalod all times are taken relative to the start time.
Listing 3 discovers the behaviour of setInterval. Line 1 initialize the global counter k by 0. Line 2 saves the timerid of the setInteval call in line 2-8 by tda. setInterval invokes the anonymous function from its first parameter in line 2-8 periodically every 100 ms. Line 3 increases the global conuter k by every call. After three invokations stops the call of clearInterval in line 5 the process. Unless cancelation line 8 produces and logs workload.
The output of Listing 3 shows lisiting 4.
Listing 5 discover the behaviour of setTimeout. The first line of the listing initializes the global counter kk by 0. Line 2-7 defines the function set. Again every invokation increases the global counter kk in line 3 and the call of logWorkload produces and logs the workload. Unless 6 invokations are done line 6 calls itself recursivley by setTimeout after 100 ms.
The output of listing 5 shows listing 6. The first call of set is done synchronous by line 9 of listing 5. The second call starts after a delay of 100 ms after finishing the first call at 158 ms. So in contrast to setInterval setTimeout is not exactly periodically, but can be stoped logically without explicit cancelation by its timerid.
Lisiting 7 shows the combination of both sub programs. The first three calls are regular. But the second invocation of setInterval, line 4, can not take place after 200ms, because the second call of setTimeout is still occupying the single Javascript Thread. So setInterval starts soon as possible at 222 ms.
Conclusion
setTimeout and setInterval calls custom functions asynchronous by a given delay. setInterval works periodically, setTimeout relative to its own call. But in both cases may the delay enlarged by function calls occupying the single Javascript thread before.