JavaScript timer function loop

The Timers module in Node.js contains functions that execute code after a set period of time. Timers do not need to be imported via require(), since all the methods are available globally to emulate the browser JavaScript API. To fully understand when timer functions will be executed, it's a good idea to read up on the Node.js Event Loop.

Controlling the Time Continuum with Node.js

The Node.js API provides several ways of scheduling code to execute at some point after the present moment. The functions below may seem familiar, since they are available in most browsers, but Node.js actually provides its own implementation of these methods. Timers integrate very closely with the system, and despite the fact that the API mirrors the browser API, there are some differences in implementation.

"When I say so" Execution ~ setTimeout()

setTimeout() can be used to schedule code execution after a designated amount of milliseconds. This function is similar to window.setTimeout() from the browser JavaScript API, however a string of code cannot be passed to be executed.

setTimeout() accepts a function to execute as its first argument and the millisecond delay defined as a number as the second argument. Additional arguments may also be included and these will be passed on to the function. Here is an example of that:

function myFunc(arg) {
  console.log(`arg was => ${arg}`);
}

setTimeout(myFunc, 1500, 'funky');

The above function

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
1 will execute as close to 1500 milliseconds (or 1.5 seconds) as possible due to the call of setTimeout().

The timeout interval that is set cannot be relied upon to execute after that exact number of milliseconds. This is because other executing code that blocks or holds onto the event loop will push the execution of the timeout back. The only guarantee is that the timeout will not execute sooner than the declared timeout interval.

setTimeout() returns a

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object that can be used to reference the timeout that was set. This returned object can be used to cancel the timeout ( see
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
5 below) as well as change the execution behavior (see
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
6 below).

"Right after this" Execution ~ console.log('before immediate'); setImmediate((arg) => { console.log(`executing immediate: ${arg}`); }, 'so immediate'); console.log('after immediate'); 7

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 will execute code at the end of the current event loop cycle. This code will execute after any I/O operations in the current event loop and before any timers scheduled for the next event loop. This code execution could be thought of as happening "right after this", meaning any code following the
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 function call will execute before the
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 function argument.

The first argument to

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 will be the function to execute. Any subsequent arguments will be passed to the function when it is executed. Here's an example:

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');

The above function passed to

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 will execute after all runnable code has executed, and the console output will be:

before immediate
after immediate
executing immediate: so immediate

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 returns an
before immediate
after immediate
executing immediate: so immediate
4 object, which can be used to cancel the scheduled immediate (see
before immediate
after immediate
executing immediate: so immediate
5 below).

Don't get

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7 confused with
before immediate
after immediate
executing immediate: so immediate
7. There are some major ways they differ. The first is that
before immediate
after immediate
executing immediate: so immediate
7 will run before any
before immediate
after immediate
executing immediate: so immediate
4s that are set as well as before any scheduled I/O. The second is that
before immediate
after immediate
executing immediate: so immediate
7 is non-clearable, meaning once code has been scheduled to execute with
before immediate
after immediate
executing immediate: so immediate
7, the execution cannot be stopped, just like with a normal function. Refer to to better understand the operation of
before immediate
after immediate
executing immediate: so immediate
7.

"Infinite Loop" Execution ~ function intervalFunc() { console.log('Cant stop me now!'); } setInterval(intervalFunc, 1500); 3

If there is a block of code that should execute multiple times,

function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);
3 can be used to execute that code.
function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);
3 takes a function argument that will run an infinite number of times with a given millisecond delay as the second argument. Just like setTimeout(), additional arguments can be added beyond the delay, and these will be passed on to the function call. Also like setTimeout(), the delay cannot be guaranteed because of operations that may hold on to the event loop, and therefore should be treated as an approximate delay. See the below example:

function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);

In the above example,

function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);
8 will execute about every 1500 milliseconds, or 1.5 seconds, until it is stopped (see below).

Just like setTimeout(),

function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);
3 also returns a
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object which can be used to reference and modify the interval that was set.

Clearing the Future

What can be done if a

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 or
before immediate
after immediate
executing immediate: so immediate
4 object needs to be cancelled? setTimeout(),
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
7, and
function intervalFunc() {
  console.log('Cant stop me now!');
}

setInterval(intervalFunc, 1500);
3 return a timer object that can be used to reference the set
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 or
before immediate
after immediate
executing immediate: so immediate
4 object. By passing said object into the respective
const timeoutObj = setTimeout(() => {
  console.log('timeout beyond time');
}, 1500);

const immediateObj = setImmediate(() => {
  console.log('immediately executing immediate');
});

const intervalObj = setInterval(() => {
  console.log('interviewing the interval');
}, 500);

clearTimeout(timeoutObj);
clearImmediate(immediateObj);
clearInterval(intervalObj);
9 function, execution of that object will be halted completely. The respective functions are
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
5,
before immediate
after immediate
executing immediate: so immediate
5, and
const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});
2. See the example below for an example of each:

const timeoutObj = setTimeout(() => {
  console.log('timeout beyond time');
}, 1500);

const immediateObj = setImmediate(() => {
  console.log('immediately executing immediate');
});

const intervalObj = setInterval(() => {
  console.log('interviewing the interval');
}, 500);

clearTimeout(timeoutObj);
clearImmediate(immediateObj);
clearInterval(intervalObj);

Leaving Timeouts Behind

Remember that

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 objects are returned by
const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});
4 and
const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});
5. The
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object provides two functions intended to augment
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 behavior with
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
6 and
const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});
9. If there is a
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object scheduled using a require()1 function,
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
6 can be called on that object. This will change the behavior slightly, and not call the
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object if it is the last code to execute. The
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object will not keep the process alive, waiting to execute.

In similar fashion, a

console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object that has had
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
6 called on it can remove that behavior by calling
const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});
9 on that same
console.log('before immediate');

setImmediate((arg) => {
  console.log(`executing immediate: ${arg}`);
}, 'so immediate');

console.log('after immediate');
4 object, which will then ensure its execution. Be aware, however, that this does not exactly restore the initial behavior for performance reasons. See below for examples of both:

const timerObj = setTimeout(() => {
  console.log('will i run?');
});

// if left alone, this statement will keep the above
// timeout from running, since the timeout will be the only
// thing keeping the program from exiting
timerObj.unref();

// we can bring it back to life by calling ref() inside
// an immediate
setImmediate(() => {
  timerObj.ref();
});

Further Down the Event Loop

There's much more to the Event Loop and Timers than this guide has covered. To learn more about the internals of the Node.js Event Loop and how Timers operate during execution, check out this Node.js guide: The Node.js Event Loop, Timers, and process.nextTick().

How to repeat timer function in JavaScript?

Use setInterval() to specify a function to repeat with a time delay between executions. Again, two parameters are passed to setInterval() : the function you want to call, and the amount of time in milliseconds to delay each call of the function . setInterval() will continue to execute until it is cleared.

How to make a loop with timer in JavaScript?

The two key methods to use with JavaScript are:.
setTimeout(function, milliseconds ) Executes a function, after waiting a specified number of milliseconds..
setInterval(function, milliseconds ) Same as setTimeout(), but repeats the execution of the function continuously..

Can I use setTimeout in for loop?

The setTimeout function callback isn't triggered until the for loop execution has completed. When the for loop has finished executing the value of i is 7. Now when the setTimeout call begins to execute it uses the last set value of i which is 7. Hence 7 is printed in all the setTimeout callbacks.

Is there a timer function in JavaScript?

There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.