我尝试在chrome调试器工具中运行脚本。在脚本中,我要等待(例如,在渲染动画后等待按钮)。我怎样才能做到这一点?我找到了一些类似的解决方案:
async function test () {
console.log('1');
await setTimeout(function() {
console.log('2');
}, 3000);
console.log('3');
}
我希望先打印1、2,然后三秒钟后再打印3。但是结果是1,3,然后三秒钟后再打印2。
我想通过几个顺序的动作来做。
知道我该怎么做吗?
最佳答案
您不能await
setTimeout
函数的结果,因为它不是Promise
。要执行您想做的事情,您可以创建一个Promise
在3秒后解析,这是一个示例:
async function test() {
console.log('1');
console.log('2');
await new Promise(resolve => {
setTimeout(resolve, 3000);
});
console.log('3');
}
test();
根据您的描述,似乎您想访问一些DOM元素(当它们可用时),为此提供MutationObserver,这是一个示例:
const parent = document.querySelector('#parent');
setTimeout(() => {
const button = document.createElement('button');
button.textContent = 'BUTTON';
button.id = 'targetBtn';
parent.appendChild(button);
}, 2000);
const observer = new MutationObserver((mutationList) => {
mutationList.forEach((mutationRecord) => {
if (mutationRecord.addedNodes && mutationRecord.addedNodes.length) {
const btn = [...mutationRecord.addedNodes].find(n => n.matches && n.matches('#targetBtn'));
if (btn) {
console.log('Button #' + btn.id + ' was found');
}
}
});
});
observer.observe(parent, {
childList: true
});
<div id="parent">
</div>
这样做是监视
#parent
元素的子列表以查看何时添加#targetBtn
元素。这有点过头了,更好的解决方案是监视将导致目标元素可用的事件。
关于javascript - 在Chrome调试器工具中设置超时,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58667357/