All files / src/internal/client loop.js

95.65% Statements 44/46
100% Branches 7/7
75% Functions 3/4
95.55% Lines 43/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 552x 552x 868x 346x 346x 346x 552x 552x 552x 340x 340x 552x 2x 2x 2x 2x 2x 2x 2x 2x 415x 415x 415x 415x 218x 218x 415x 415x 415x 415x 415x 415x     415x 415x  
/** @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);
		}
	};
}