ngwomo
ngwomo

Reputation: 91

How to "wait" setTimeout to finish inside function and then execute function's return

In function, const htmlCollection = document.getElemenetsByClassName('elemenet-class') is used to get desired element from DOM and some element's properties are used in return value of function (return htmlCollection[0].clientWidth).

The problem was that function's return executes before all DOM nodes are loaded so when I access htmlCollection[0] to get desired element, it gets undefined. What I tried is wrapping code inside setTimeout with 500ms offset where I can access htmlCollection[0] element but now problem is that function's return is part of main thread and executes before whole setTimeout which is asynchronous operation, so htmlCollection[0].clientWidth which should be in return value of function "lives" only inside setTimeout.

How can I "wait" for DOM to be loaded (or "wait" setTimeout to execute and retrieve contentWrapperWidth) and then execute function's return?

Code:

// first try (fails because on function return, 'content-wrapper' is not loaded in DOM)
renderPreview = () => {
let htmlString = getHTML();
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;

htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);

return htmlString;
}


// second try (fails because function's return executes before setTimeout of course - i.e. contentWrapperWidth lives only inside setTimeout and function returns htmlString with placeholder, before replacing)
renderPreview = () => {
let htmlString = getHTML();

setTimeout(() => {
const contentWrapper = document.getElementsByClassName('content-wrapper');
const contentWrapperWidth = contentWrapper[0].clientWidth;

htmlString = htmlString.replace('width_placeholder', contentWrapperWidth);
} , 500);

return htmlString;
}

Upvotes: 0

Views: 105

Answers (1)

chawki challadia
chawki challadia

Reputation: 454

you can use document.addEventListener("load", function)

that should load your function after the dom loads.

Upvotes: 1

Related Questions