我已经编写了这段代码,这让我感到惊讶。
我不明白为什么调用该函数但只在前2行执行,然后setInterval等待1秒并执行return语句。
请,有人向我解释:)
let div = document.getElementById("div1");
const updateTime = () => {
let seconds = 0;
if (seconds === 0) div.textContent = `0 sekund`;
return () => {
seconds++;
div.textContent = `${seconds} sekund`;
}
}
setInterval(updateTime(), 1000);
<div id="div1"></div>
答案 0 :(得分:1)
您立即执行updateTime(),它执行前两行,然后又立即返回在1秒后第一次运行的函数,然后在此之后每秒运行一次。
请阅读我在代码中写的注释:
let div = document.getElementById("div1");
const updateTime = () => {
// next two lines executed by updateTime() immediately
let seconds = 0; // these are remembered because you create a closure
if (seconds === 0) div.textContent = `0 sekund`;
// NOW the following function is returned and will be what is
// executed for the rest of the life of the setInterval
// The first time this returned function is called is in one second from now
return () => { // this creates a closure. It is a good way to handle vars
seconds++; // this is known only to the function
div.textContent = `${seconds} sekund`;
}
}
setInterval(
updateTime(), // execute this IMMEDIATELY
1000 // execute whatever is returned from updateTime in intervals of 1 seconds
);
<div id="div1"></div>
答案 1 :(得分:1)
updateTime
函数在您调用updateTime()
时运行。
全部运行。
关键字return
之后的部分是语法定义另一个函数。它不会立即运行,因为您没有做任何调用。
返回了另一个函数。
您正在将该函数传递给setInterval
,该函数每秒对其进行调用。