From: Ardis Lu Date: Mon, 9 Sep 2024 06:45:02 +0000 (-0700) Subject: Debounce ResizeObserver X-Git-Url: https://git.ardis.lu/?a=commitdiff_plain;h=454dcb4f1daf72072b4b52fdb365c8e46e38ef2f;p=ardislu.dev Debounce ResizeObserver Further improves performance by not recalculating on every pixel resized --- diff --git a/script.js b/script.js index eaf0787..024dce4 100644 --- a/script.js +++ b/script.js @@ -61,15 +61,23 @@ async function fetchPostMetadata() { return metadata; } +function debounce(fn, wait) { + let timeoutId; + return (...args) => { + clearTimeout(timeoutId); + timeoutId = setTimeout(() => fn.apply(this, args), wait); + } +} + // Sets grid-row-end for each card when the homepage is resized. Required to implement masonry layout. -const observer = new ResizeObserver(home => { - for (const card of home.children) { +const observer = new ResizeObserver(debounce(entries => { + for (const card of entries[0].target.children) { const contentHeight = Array.from(card.children).reduce((acc, cur) => acc + cur.clientHeight, 0); const cardHeight = contentHeight + 128; // 6 * 16px gaps + 2 * 16px padding card.style.gridRowEnd = `span ${Math.ceil(cardHeight / 16)}`; // 16px grid gap card.style.maxBlockSize = `${cardHeight}px`; } -}); +}, 200)); /* Constructs the
element used on the homepage from the CMS metadata Map object. */ function buildHomeComponent(metadata) {