我正在用 JS 构建一个脚本,该脚本将在网页上运行并按顺序修改元素。我需要能够等待/ sleep ,同时将整个进程包含在正在运行的函数中。下面的示例是不言自明的,是我需要帮助的一个非常简单但全面的示例:
<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 循环不是一个好主意。我见过许多与此类似的其他问题,但我不明白如何调整其他答案来解决我需要帮助的问题:
- 一个中央函数/循环作用于不同的“步骤”,并在这些步骤中具有多个不同的等待/ sleep
- 需要避免使用无序执行的内容
最佳答案
为了让它看起来漂亮,你可以使用 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>
关于javascript - javascript 中等待/ sleep 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45155668/