All files / src/internal/client loop.js

93.47% Statements 43/46
87.5% Branches 7/8
100% Functions 4/4
93.33% Lines 42/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 544x 544x 760x       544x 544x 544x 430x 430x 544x 2x 2x 2x 2x 2x 2x 2x 2x 407x 407x 407x 407x 214x 214x 407x 407x 407x 407x 407x 407x 337x 337x 407x 407x  
/** @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);
		}
	};
}