我正在JS中构建一个脚本,该脚本将在网页上运行并按顺序修改元素。我需要能够在运行函数中包含整个过程时等待/休眠。下面的例子是自我解释的,是一个非常简单而又全面的例子,说明了我需要帮助的地方:
<body>
<button id="button-start" onclick="updateStatus('started')">START!</button>
<button id="button-1" onclick="console.log('step_1')">button-1</button>
<button id="button-2" onclick="console.log('step_2')">button-2</button>
<script>
var status = 'stopped';
var step = 'initial';
function updateStatus(newStatus) {
status = newStatus;
script();
}
function wait(msec) {
var now = new Date().getTime();
while(new Date().getTime() < now + msec){ /* do nothing */ }
}
function script() {
while (status == 'started') {
if (step == 'initial') {
console.log('Script started');
step = 'click_button1';
}
if (step == 'click_button1') {
document.getElementById("button-1").click();
wait(1000)
step = 'click_button2';
}
if (step == 'click_button2') {
document.getElementById("button-2").click();
step = 'done';
}
if (step == 'done') {
status = 'stopped';
}
}
console.log('Script done');
}
</script>
</body>
这正是我需要它的方式,但显然使用while循环并不是一个好主意。我已经看到了许多类似的问题,但我不明白如何调整其他答案以解决我需要帮助的问题:
答案 0 :(得分:2)
为了让它看起来不错,您可以使用async和Promise在setTimeout
之后解析。
注意这一行
await wait(1000)
<body>
<button id="button-start" onclick="updateStatus('started')">START!</button>
<button id="button-1" onclick="console.log('step_1')">button-1</button>
<button id="button-2" onclick="console.log('step_2')">button-2</button>
<script>
var status = 'stopped';
var step = 'initial';
function updateStatus(newStatus) {
status = newStatus;
script();
}
function wait(msec) {
return new Promise(res => {setTimeout(()=>{res()}, msec)})
}
async function script() {
while (status == 'started') {
if (step == 'initial') {
console.log('Script started');
step = 'click_button1';
}
if (step == 'click_button1') {
document.getElementById("button-1").click();
await wait(1000)
step = 'click_button2';
}
if (step == 'click_button2') {
document.getElementById("button-2").click();
step = 'done';
}
if (step == 'done') {
status = 'stopped';
}
}
console.log('Script done');
}
</script>
</body>