I have a setInterval function which is calculating the difference between a certain date and the current time. When this difference reaches less than an hour, I want to run some code that should only be executed once.
const countdownDate = new Date('March 15, 2021 11:30:00').getTime();
const HOUR_IN_MILLISECONDS = 3600000;
let ticker = setInterval(() => {
let now = new Date().getTime();
let duration = countdownDate - now;
if (duration < HOUR_IN_MILLISECONDS) {
console.log('This will keep running');
}
if (duration === 0) {
clearInterval(ticker);
}
}, 1000);
One method I've found to achieve this is by setting a global flag that is flipped once the function has run once.
let bar = false;
function foo() {
if (!bar) {
console.log('This will only run once');
}
bar = true;
}
let ticker = setInterval(() => {
if (duration < HOUR_IN_MILLISECONDS) {
foo();
}
}, 1000);
Another way that works is to fire a custom event and register a one-off event handler. However i'm not sure if firing an event every second is less performant than the previous solution.
const foo = new Event('foo');
document.addEventListener('foo', () => {
console.log('This will only run once');
}, { once: true });
let ticker = setInterval(() => {
if (duration < HOUR_IN_MILLISECONDS) {
document.dispatchEvent(foo);
}
}, 1000);
I'm assuming there must be a better way to achieve the desired behaviour. I understand that it's not best practice to try run something only once inside a setInterval but i've not been able to find any other workarounds so far.