Selenium wait-for-DOM-to-load hack

I am using Selenium (Web driver) a lot these days and it seems to me that there aren’t any real patterns how to use it correctly. Selenium usage may differ with every single webpage.

Consider the use case when you use Ajax to load the content of your webpage. Given that the DOM build relies on async function calls Selenium needs to wait for a given element to render in order to continue UI testing.

The problem rises when the built in waiting-for-DOM functions just don’t seem to work. There are hundreds of tips and solutions out there which may work in some situations but sometimes not at all (like Protractor, driver.wait, webdriver.until.elementLocated).

I happened to come up with a little hack for this problem which seems to work in the most cases:

sleep(seconds) {
const e = new Date().getTime() + (seconds * 1000);
while (new Date().getTime() <= e) {};
// stops selenium execution for 5 seconds
async seleniumTestFunction() {
await this.driver

I suggest you only to use this hack when no above mentioned built in function works. This hack above halts Selenium sync/semi-sync execution flow and wins time for the DOM to render elements.