Skip to content

Instantly share code, notes, and snippets.

@dalenguyen
Created April 2, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalenguyen/434525efa0c557fe174d37aa8b734646 to your computer and use it in GitHub Desktop.
Save dalenguyen/434525efa0c557fe174d37aa8b734646 to your computer and use it in GitHub Desktop.
Wait for Element to Exist (JavaScript)
// HTML
<!-- Comment or Uncomment the div for return true / false -->
<div id="the-element"></div>
// JAVASCRIPT
// Wait for element for 4s
const waitForElement = async (elementId, timeWait = 4) => {
return new Promise((resolve, reject) => {
let tempTime = 0
const checkExist = setInterval(function() {
if ($(elementId).length) {
console.log('Exists');
clearInterval(checkExist);
resolve(true)
} else if (!$(elementId).length && tempTime > timeWait) {
console.log(`Doesn't exist...`);
clearInterval(checkExist);
reject(false)
} else {
tempTime++
console.log(`Waiting for ${elementId}`, tempTime)
}
}, 1000); // check every 1000ms
})
}
waitForElement('#the-element')
.then(res => console.log(`Exist`, res))
.catch(error => console.log(`Exist`, error))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment