Skip to content

Instantly share code, notes, and snippets.

@alejoasotelo
Last active July 21, 2022 19:14
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 alejoasotelo/cf34dc718615cf40ab89c904d8674e69 to your computer and use it in GitHub Desktop.
Save alejoasotelo/cf34dc718615cf40ab89c904d8674e69 to your computer and use it in GitHub Desktop.
TaskQueue es para agregar tareas que se ejecuten secuencialmente cada cierto intervalo de segundos.
/**
@author Alejo Sotelo <alejosotelo.com.ar>
@date 2022-07-20
Las tareas se ejecutan secuencialmente según el intervalo configurado.
Si agrego 3 task/tareas, se van a ejecutar en el orden que las agrego.
Cada task tiene un callback (function) que tiene que devolver true (se elimina la tarea y no se ejecuta más) o false (se sigue ejecutando).
var fiveSeconds = 5 * 1000;
var myTasks = new TaskQueue(fiveSeconds);
myTasks.addTask('one', _ => { console.log('Executing one'); return true; }); // se ejecute una sola vez
var i = 0;
myTasks.addTask('two', _ => { console.log('Executing two ' + ++i); return i >= 2; }); // se ejecute 2 veces (i>=2)
var j = 0;
myTasks.addTask('three', _ => {
console.log('Executing three', j);
return new Promise(resolve => {
setTimeout(_ => {
console.log('Finishing three', j);
resolve(j++ > 2);
}, 2000);
});
}); // se ejecute 2 veces (i>=2)
myTasks.run();
*/
window.requestAnimFrame = (function() {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var TaskQueue = function(intervalSeconds, debug) {
intervalSeconds = intervalSeconds || 1000;
var start = 0,
running = false,
debug = typeof debug == 'boolean' ? debug : false,
queue = [],
i = 0;
this.run = _ => {
start = performance.now();
running = true;
i = 0;
this.loop();
}
this.stop = _ => {
running = false;
}
this.addTask = (name, callback) => {
if (this.getTask(name)) {
return false;
}
queue.push({
name,
callback
});
}
this.getTask = (name) => {
return queue.find(i => i.name == name);
}
this.getTasks = () => {
return queue;
}
this.removeTask = (name) => {
var index = queue.findIndex(i => i.name == name);
if (index >= 0) {
queue.splice(index, 1);
}
}
this.removeAllTasks = () => {
queue = [];
}
this.isRunning = () => running;
this.loop = async _ => {
if (queue.length == 0) {
if (debug) {
console.debug('No hay tareas');
}
return false;
}
var now = performance.now();
var delta = now - start;
if (delta >= intervalSeconds) {
if (debug) {
var TaskQueue = function (intervalSeconds, debug) {
intervalSeconds = intervalSeconds || 1000;
debug = typeof debug == 'boolean' ? debug : false;
var timeStart = 0,
running = false,
queue = [],
i = 0;
this.start = _ => {
timeStart = performance.now();
running = true;
i = 0;
this.loop();
}
this.stop = _ => {
running = false;
}
this.addTask = (name, callback) => {
if (this.getTask(name)) {
return false;
}
queue.push({
name,
callback
});
}
this.getTask = (name) => {
return queue.find(i => i.name == name);
}
this.getTasks = () => {
return queue;
}
this.removeTask = (name) => {
var index = queue.findIndex(i => i.name == name);
if (index >= 0) {
queue.splice(index, 1);
}
}
this.removeAllTasks = () => {
queue = [];
}
this.isRunning = () => running;
this.loop = async _ => {
if (queue.length == 0) {
if (debug) {
console.debug('No hay tareas');
}
return false;
}
var now = performance.now();
var delta = now - timeStart;
if (delta >= intervalSeconds) {
if (debug) {
console.debug(`Task *${queue[i].name}* running...`, +new Date());
}
var haveToRemove = await queue[i].callback();
timeStart = performance.now();
if (haveToRemove) {
queue.splice(i, 1);
if (queue.length == 0) {
running = false;
}
i--;
}
i++;
if (i > queue.length - 1) {
i = 0;
}
}
if (running) {
requestAnimFrame(this.loop);
} else if (debug) {
if (queue.length == 0) {
console.debug('All tasks have been completed');
} else {
console.debug('Task stopped');
}
}
}
}
@alejoasotelo
Copy link
Author

Casos de uso

  • Extensión de Chrome/Firefox que ejecute tareas cada cierto tiempo para buscar productos a X precio, stock, etc.
  • Simular cronjobs?

@alejoasotelo
Copy link
Author

Mejore el script para usar requestAnimationFrame en vez de setTimeout.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment