我想简单地设置每次点击之间的延迟。
下面显示的是我创建的脚本。按我想要的方式单击每个元素,效果很好。问题在于,它几乎同时单击每个元素,这使我感到非常糟糕。
原始代码。
var timerVar = setInterval (function() {DoMeEverySecond (); }, 5000); //
<< set to 2 seconds.
function DoMeEverySecond ()
{
(function() {
document.getElementsByName("zTab")[0].click();
document.getElementsByName("zButton")[0].click();
document.getElementsByName("zClose")[0].click();
})();
}
可以做这样的事情吗?
var timerVar = setInterval (function() {DoMeEverySecond (); }, 5000); //
<< set to 2 seconds.
function DoMeEverySecond ()
{
(function() {
document.getElementsByName("zTab")[0].click();
-----------A DELAY HERE!-----------
document.getElementsByName("zButton")[0].click();
---------- ANOTHER ONE HERE! ----------------
document.getElementsByName("zClose")[0].click();
})();
}
代码很简单,我尽力解释了一下。有人可以帮我解决这段代码吗
最佳答案
这是一个潜在解决方案的现场演示。请参阅内联注释:
// Lets just add some logging here for when the buttons are clicked
document.querySelectorAll('.z-tab').forEach(element => {
element.addEventListener('click', e => console.log('Z Tab'));
});
document.querySelectorAll('.z-button').forEach(element => {
element.addEventListener('click', e => console.log('Z Button'));
});
document.querySelectorAll('.z-close').forEach(element => {
element.addEventListener('click', e => console.log('Z Close'));
});
// Let's take advantage of async/await
async function DoMeEverySecond () {
const elementClassNames = ['.z-tab', '.z-button', '.z-close'];
for (let i = 0; i < elementClassNames.length; i++) {
const element = document.querySelectorAll(elementClassNames[i])[0];
await delayFor(1000); // Let's wait 1000ms between each click
element.click()
}
}
// Delay function that will resolve a promise after the setTimeout delay has been passed.
function delayFor(delay) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, delay);
});
}
DoMeEverySecond ();
<h2>Z Tabs</h2>
<button class="z-tab">1</button> <button class="z-tab">2</button>
<h2>Z Buttons</h2>
<button class="z-button">1</button> <button class="z-button">2</button>
<h2>Z Close</h2>
<button class="z-close">1</button> <button class="z-close">2</button>