Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Scheduler
let events = [];
let timeout = null;
let interval = 100;
const getScheduled = () => {
let now = Date.now();
return events.filter(event => {
return (event.lastInvoked + event.interval) < now;
});
};
const start = () => {
if (timeout) {
stop();
}
timeout = setTimeout(scheduler, interval);
};
const stop = () => {
timeout = clearTimeout(timeout);
};
const add = (interval, repeat, callback) => {
let lastInvoked = Date.now();
let id = Math.random().toString(36).substring(2, 10);
let event = { id, interval, repeat, callback, lastInvoked };
events.push(event);
// Start the scheduler if not aleady started.
if (!timeout && events.length > 0) {
start();
}
return event;
};
const remove = event => {
let index = events.findIndex(e => e.id === event.id);
if (index !== -1) {
events.splice(index, 1);
if (timeout && events.length === 0) {
stop();
}
}
};
const scheduler = () => {
let scheduled = getScheduled();
scheduled.forEach(event => {
event.callback();
event.lastInvoked = Date.now();
if (!event.repeat) {
remove(event);
}
});
if (timeout) {
start();
}
};
module.exports = {
add,
remove
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.