JavaScript: Infinite timer loop

From The Travis van der Font Wiki
Jump to: navigation, search
This functionality is ideal for processing without async / await functions or endless ajax stream processing.
// 1000 milliseconds = 1 second
var ms_timer = 1000;

setTimeout(function next()
{
    processingFunction();
    setTimeout(next, ms_timer);
},
ms_timer);

function processingFunction()
{
    // ..... <processing code here>
}
Note: Using the setTimeout pattern above makes sure that the processor gets a set value of milliseconds break between each call, no matter how long the function takes to execute. To improve page performance avoid using setInterval which does not to wait for the function to finish execution and will also avoid memory leaks.