I am using addEventListener to execute some different code whenever one of a certain number of different buttons is clicked.
I would like to have control over when this code is executed. More specifically, I would like click events for all these buttons to be queued so that at any point in the code I can fetch the oldest event that has not yet been fetched, remove it from the queue and execute the corresponding code.
For example, in Rust I was doing this by using the poll() and read() functions from the event module of the crossterm crate ( https://docs.rs/crossterm/latest/crossterm/event/index.html ). The poll() function tells me whether there is an event in the queue and the read() function gives me the oldest event and removes it from the queue.
Is there an easy way to this in JavaScript?
Thanks!
>Solution :
You could just have a workQueue = [], push functions onto it, and then whenever you want to run the "next job", call workQueue.shift()(). E.g. if you want to only run one job a second, you could do:
const workQueue = [];
let i = 0;
document.querySelector('#add').addEventListener('click', () => {
const job = () => {
console.log(i++);
};
workQueue.push(job);
});
document.querySelector('#run').addEventListener('click', () => {
runNextJob()
});
const runNextJob = () => workQueue.length && workQueue.shift()()
setInterval(() => {
runNextJob()
}, 1000);
<button id="add">Add Event</button>
<button id="run">Run Now</button>
That being said, you could also just run the job immediately on click and you’d get the same effect, only faster. But this does give the benefit of being able to "queue up" work, and then whenever you want you can tell it to do the next unit.