有代码
function longTimeFunction() {
for (i = 0; i < 100000000; i++) {
//.do somethig
}
}
function foo() {
document.getElementById('mydiv').innerText = 'Start';
console.log(document.getElementById('mydiv').innerText);
longTimeFunction(); // call long time
document.getElementById('mydiv').innerText = 'First call complete';
console.log(document.getElementById('mydiv').innerText);
longTimeFunction(); // call long time
document.getElementById('mydiv').innerText = 'Second call complete';
console.log(document.getElementById('mydiv').innerText);
}
foo();
<div id="mydiv"></div>
文本以正确的时间间隔写入控制台。
div 元素中的文本不会改变。
是否可以更改div的文本?
我尝试改变风格。我尝试将显示更改为“无”,然后通过 setTimeout 更改回“阻止”。尝试添加子元素。也是通过setTimeout。
没有结果。
如果“longTimeFunction()”的目的只是引起一些延迟,那么我建议将
foo()
制作为异步函数,并从 await
发出承诺以造成人为延迟。setTimeout
这是一个例子:
async function foo(){
console.log("foo called");
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("This message appears 1000ms after the first!");
}
您可以将其扩展为它自己的辅助函数,以便在需要延迟时轻松调用:
(async()=>{
console.log("foo called");
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("This message appears 1000ms after the first!");
})();
如果您希望每 x 秒调用一次
function delay(timeInMS) {
return new Promise(resolve => setTimeout(resolve, timeInMS));
}
async function foo(){
// do some div stuff like your example
await delay(2000) // wait for 2 seconds
// do some more div stuff
await delay(1000) // wait for 1 second
// do the last div stuff
}
,那么只需在
longTimeFunction()
内调用它即可
setInverval
这是一个例子:
setInterval(someFunc,1000);
setInterval(()=>console.log("This is printed every 2 seconds!"),2000);
function foo() {
document.getElementById('mydiv').innerText = 'Start';
console.log(document.getElementById('mydiv').innerText);
setTimeout(() => {
document.getElementById('mydiv').innerText = 'First call complete';
console.log(document.getElementById('mydiv').innerText);
setTimeout(() => {
document.getElementById('mydiv').innerText = 'Second call complete';
console.log(document.getElementById('mydiv').innerText);
}, 1000);
}, 1000);
}
foo();