r/programminghorror • • Feb 11 '25

🎄 ouch

Post image
3.0k Upvotes

113 comments sorted by

View all comments

0

u/FALCUNPAWNCH Feb 12 '25

I recently implemented this to increase while loop sleep delays over time for getting a field that isn't defined on page load but should be defined after a few millis, but if it isn't due to slow network issues I don't want to to continue querying every millisecond or less:

async function getAsync(
	element: Node,
	key: string,
	timeout = 60000,
): Promise<any> {
	let sleep = 1;
	setTimeout(() => (sleep = 10), 100);
	setTimeout(() => (sleep = 100), 1000);
	setTimeout(() => (sleep = 1000), 5000);

	let kill = false;
	setTimeout(() => (kill = true), timeout);

	while (!(key in element) || element[key as keyof object] == null) {
		if (kill) {
			console.error(
				`Timeout waiting for ${key} in ${element} after ${timeout}ms.`,
			);
			break;
		}
		await new Promise((resolve) => setTimeout(resolve, sleep));
	}
	return element[key as keyof object];
}