All files / src/internal/client loop.js

100% Statements 46/46
100% Branches 8/8
100% Functions 4/4
100% Lines 45/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 462x 2x 2x 2x 2x 2x 2x 2x 2x 554x 554x 814x 276x 276x 276x 554x 554x 554x 344x 344x 554x 2x 2x 2x 2x 2x 2x 2x 2x 431x 431x 431x 431x 244x 244x 431x 431x 431x 431x 431x 431x 225x 225x 431x 431x  
/** @import { TaskCallback, Task, TaskEntry } from '#client' */
import { raf } from './timing.js';
 
// TODO move this into timing.js where it probably belongs
 
/**
 * @param {number} now
 * @returns {void}
 */
function run_tasks(now) {
	raf.tasks.forEach((task) => {
		if (!task.c(now)) {
			raf.tasks.delete(task);
			task.f();
		}
	});
 
	if (raf.tasks.size !== 0) {
		raf.tick(run_tasks);
	}
}
 
/**
 * Creates a new task that runs on each raf frame
 * until it returns a falsy value or is aborted
 * @param {TaskCallback} callback
 * @returns {Task}
 */
export function loop(callback) {
	/** @type {TaskEntry} */
	let task;
 
	if (raf.tasks.size === 0) {
		raf.tick(run_tasks);
	}
 
	return {
		promise: new Promise((fulfill) => {
			raf.tasks.add((task = { c: callback, f: fulfill }));
		}),
		abort() {
			raf.tasks.delete(task);
		}
	};
}