Skip to content

Instantly share code, notes, and snippets.

@g8up
Last active August 28, 2023 11:40
Show Gist options
  • Save g8up/4b60cadf1a307673aef9c23cd1191411 to your computer and use it in GitHub Desktop.
Save g8up/4b60cadf1a307673aef9c23cd1191411 to your computer and use it in GitHub Desktop.
轮询检测页面节点
<!DOCTYPE html>
<html lang="zh-cmn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>死宅程序员</title>
<!-- 配套视频讲解:https://www.bilibili.com/video/BV1b94y1z74s/ -->
</head>
<body>
<script>
const $ = selector => document.querySelector(selector);
/**
* 循环执行指定逻辑
* @param func 任务,如果返回值为true 则退出循环
* @param hz 频率,单位:s
* @param count 循环次数
*/
const loop = (func, count = 10, hz = 1)=> {
const inner = (callback, count)=> {
count -= 1;
if( count < 0 ) {
callback(false);
return;
}
setTimeout(()=>{
if(func()) {
callback(true);
}
else {
inner(callback, count);
}
}, hz * 1e3);
};
return new Promise((resolve, reject) => {
inner(resolve, count);
});
}
const waitForElement = (selector, count, hz)=>{
return loop(()=>$(selector), count, hz)
.then(isExist=>{
console.log(isExist ? 'Exist' : 'not exist');
if(isExist) {
return $(selector);
}else{
return null;
}
});
};
const append = ()=>{
const div = document.createElement('div');
div.id='app';
document.body.appendChild(div);
console.log('app append');
}
console.log('start')
setTimeout(append, 2000);
waitForElement('#app', 3)
.then(el=>{
if(el) {
el.textContent = 'Hello world!';
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment