JavaScript 如何执行setInterval函数时第一次立即执行而没有延迟
setInterval()方法总是在第一次使用两种方法后延迟后调用函数:
方法1:在执行setInterval之前调用函数一次:
可以简单地在使用setInterval函数之前调用函数一次。这将立即执行函数一次,然后可以使用所需的回调函数设置setInterval()函数。
创建一个新函数,该函数首先包含对函数的调用,然后调用setInterval()函数。这将有助于模拟setInterval()函数在第一次执行时没有延迟。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to execute setInterval function without
delay for the first time in JavaScript ?
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Execute the setInterval function
without delay the first time
</b>
<p>
Click on the button to execute the
setInterval() function without delay.
</p>
<button onclick="startSetInterval()">
Start immediate setInterval
</button>
<script type="text/javascript">
let count = 1;
function exampleFunction() {
console.log('Function Executed! ' + count);
count = count + 1;
}
function noDelaySetInterval(func, interval) {
func();
return setInterval(func, interval);
}
function startSetInterval() {
noDelaySetInterval(exampleFunction, 3000);
}
</script>
</body>
</html>
输出:
- 点击按钮后立即发生:

- 等待3秒后发生:

方法2:在setInterval函数内使用立即调用函数
立即执行函数表达式(IIFE)是一种在声明后立即被调用的函数类型。这个特性可以在setInterval()函数的回调中使用,因为一旦声明后,它会立即执行一次,然后在指定的延迟之后开始实际的setInterval()函数调用。这将帮助模拟没有延迟的setInterval()函数的第一次调用。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Execute the setInterval function
without delay the first time
</title>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Execute the setInterval function
without delay the first time
</b>
<p>
Click on the button to execute the
setInterval() function without delay.
</p>
<button onclick="startSetInterval()">
Start immediate setInterval
</button>
<script type="text/javascript">
function startSetInterval() {
let count = 1;
setInterval(function exampleFunction() {
console.log('Function Executed! ' + count);
count = count + 1;
return exampleFunction;
}(), 3000);
}
</script>
</body>
</html>
输出:
- 点击按钮后立即:

- 等待3秒后:

极客教程