Created
April 2, 2020 18:48
-
-
Save dalenguyen/434525efa0c557fe174d37aa8b734646 to your computer and use it in GitHub Desktop.
Wait for Element to Exist (JavaScript)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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