From d83b69bb7f9a8dd6fb0156b164e740016df2fbe2 Mon Sep 17 00:00:00 2001 From: Bitshifter-9 Date: Tue, 2 Dec 2025 09:21:40 +0530 Subject: [PATCH] Fix memory leak in onLoadById function Add timeout mechanism to prevent setInterval from running indefinitely when the target element is never found. The function now stops checking after 5 seconds (50 attempts * 100ms) to prevent memory leaks when users navigate away before the element loads. Also improved JSDoc comments to use proper @param annotations. --- simplq/src/utils/scrollingOperations.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/simplq/src/utils/scrollingOperations.js b/simplq/src/utils/scrollingOperations.js index 00fe8921..3f68a2bf 100644 --- a/simplq/src/utils/scrollingOperations.js +++ b/simplq/src/utils/scrollingOperations.js @@ -31,17 +31,26 @@ export const smoothScrollToHomePageTop = (history) => { /** * Execute a callback as soon as an element is available on the DOM. + * The function will stop checking after 5 seconds to prevent memory leaks. * - * id - element id to wait on - * callback - callback to execute as soon as the element becomes available. The - * element is passed to the callback and it is triggered. + * @param {string} id - element id to wait on + * @param {Function} callback - callback to execute as soon as the element becomes available. + * The element is passed to the callback when it is triggered. * */ export const onLoadById = (id, callback) => { + const maxAttempts = 50; // 50 attempts * 100ms = 5 seconds + let attempts = 0; + const checkAndExecute = setInterval(() => { const element = document.getElementById(id); + attempts += 1; + if (element) { callback(element); clearInterval(checkAndExecute); + } else if (attempts >= maxAttempts) { + // Element not found after timeout, clear interval to prevent memory leak + clearInterval(checkAndExecute); } }, 100); };