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 542x 542x 812x 286x 286x 286x 542x 542x 542x 332x 332x 542x 2x 2x 2x 2x 2x 2x 2x 2x 419x 419x 419x 419x 238x 238x 419x 419x 419x 419x 419x 419x 197x 197x 419x 419x  
/** @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);
		}
	};
}