Skip to content

Instantly share code, notes, and snippets.

@nblackburn
Created January 30, 2019 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblackburn/38dee47a37b7e139ddf09eef59c497fc to your computer and use it in GitHub Desktop.
Save nblackburn/38dee47a37b7e139ddf09eef59c497fc to your computer and use it in GitHub Desktop.
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