All files / src/internal/client loop.js

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

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 452x 2x 2x 2x 2x 2x 2x 2x 544x 544x 860x 318x 318x 318x 544x 544x 544x 334x 334x 544x 2x 2x 2x 2x 2x 2x 2x 2x 439x 439x 439x 439x 216x 216x 439x 439x 439x 439x 439x 439x 183x 183x 439x 439x  
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 {import('#client').TaskCallback} callback
 * @returns {import('#client').Task}
 */
export function loop(callback) {
	/** @type {import('#client').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);
		}
	};
}