I am using node.js and I have a task that runs every second like so:
let queue = ["Sample Data 1", "Sample Data 2"]
const job = schedule.scheduleJob('*/1 * * * * *', function () {
console.log("Checking the queue...")
if (queue.length > 0) {
wss.broadcast(JSON.stringify({
data: queue[0]
}));
setTimeout(() => {
queue.shift();
}, queue[0].duration);
}
});
I am wondering how I can make it so that the timeout must finish before the next queue check. Could I use a de-bounce, or is there a better way?
2
Answers
You could use
to make an interval between the jobs at least 1 second and call the schedule recursively.
In that case returning a job could make not much sense, so you could collect your jobs in an array for example if needed.
But I would use an async generator to simplify the logic. A bonus here that you can execute an async code with
await
in thefor await
loop and its execution time will be counted also:The OP’s problem qualifies perfectly for a solution of mainly 2 combined techniques …
the
map
based creation of a list of async function/s (expressions), each function representing a delaying broadcast task (delaying and not delayed because the task executes immediately but delays its resolving/returning time).the creation of an async generator via an async generator-function (expression), where the latter consumes / works upon the created list of delaying tasks, and where the async generator itself will be iterated via the
for await...of
statement.In addition one needs to write kind of a
wait
function which can be achieved easily via an async function which returns aPromise
instance, where the latter resolves the promise viasetTimeout
and a customizable delay value.And since the approach is two folded, one even can customize each delay in between two tasks … one just slightly has to change the format of the to be queued data and the task generating mapper functionality (2 lines of code are effected) …