Scheduled Counter
A function that calls a given function
n
times at
interval
ms apart, starting from 0.
function createCounter(func, n, interval) {
let count = 0;
return function counter() {
func(count++);
if (count < n) {
setTimeout(counter, interval);
}
};
}
const startCounter = createCounter(console.log, 10, 500);
startCounter();
Output:
0
1
2
3
4
5
6
7
8
9
Timeout Reset Wrapper
A wrapper that delays the execution of a function until after a specified
timeout has passed since the last call, resetting the timer with each call.
function createTimeoutWrapper(func, timeout) {
let id = null;
return function() {
clearTimeout(id);
id = setTimeout(func, timeout);
}
}
const wrapper = createTimeoutWrapper(() => console.log('Hello!'), 1000);
console.log('Calling wrappers.');
wrapper();
wrapper();
wrapper();
wrapper();
wrapper();
console.log('Multiple wrappers called.');
Output:
Calling wrappers.
Multiple wrappers called.
Hello!
Custom setInterval
A custom version of setInterval
using
recursive setTimeout
.
function setMyInterval(func, interval) {
const id = { value: null };
(function callback() {
id.value = setTimeout(() => {
func();
callback();
}, interval);
})();
return id;
}
function clearMyInterval(id) {
clearTimeout(id.value);
}
const id = setMyInterval(() => {
console.log('tick');
}, 1000);
setTimeout(() => clearMyInterval(id), 5000);
Output:
tick
tick
tick
tick
Timer object
A Timer
class that repeatedly calls a
function with an incrementing counter at set intervals, and allows pausing
and resuming the timer using pause
and
continue
methods.
function Timer(func, interval) {
let id = null;
let counter = 0;
this.pause = function() {
clearInterval(id);
}
this.start = this.continue = function() {
id = setInterval(() => {
func(counter++);
}, interval);
}
}
const timer = new Timer(console.log, 1000);
console.log('Starting timer at 0s.');
timer.start();
setTimeout(() => {
console.log('Pausing timer at 5s.');
timer.pause();
}, 5010);
setTimeout(() => {
console.log('Continuing timer at 10s.');
timer.continue();
}, 10000);
setTimeout(() => {
console.log('Pausing timer at 15s.');
timer.pause();
}, 15010);
Output:
Starting timer at 0s.
0
1
2
3
4
Pausing timer at 5s.
Continuing timer at 10s.
5
6
7
8
9
Pausing timer at 15s.