JavaScript 如何每5秒钟反复调用一个函数
JavaScript中的 setInterval()方法 可以用于定期评估表达式或调用JavaScript函数。
语法:
setInterval(function, milliseconds, param1, param2, ...)
参数: 此函数接受以下参数:
- function(函数): 此参数保存了要定期调用的函数名。
- milliseconds(毫秒): 此参数保存了间隔时间,以毫秒为单位,setInterval()调用/执行上述函数。
- param1,param2,…: 一些额外的参数作为输入参数传递给函数。
返回值: 此方法返回表示由该方法设置的计时器的ID。可以通过调用clearInterval()方法并将其传递给此ID作为参数来清除/取消定时器。
示例: 假设我们想要创建一个提醒定时器,每隔5秒钟触发一次,通过JavaScript中的警报框进行提醒。
<p>
Click the button to start
timer, you will be alerted
every 5 seconds until you
close the window or press
the button to stop timer
</p>
<button onclick="startTimer()">
Start Timer
</button>
<button onclick="stopTimer()">
Stop Timer
</button>
<p id="gfg"></p>
<script>
var timer;
function startTimer() {
timer = setInterval(function() {
document.getElementById('gfg')
.innerHTML = " 5 seconds are up ";
}, 5000);
}
function stopTimer() {
document.getElementById('gfg')
.innerHTML = " Timer stopped ";
clearInterval(timer);
}
</script>
输出: 在上面的示例中,setInterval()方法重复评估一个表达式/调用一个函数。清除/取消由setInterval()方法设置的计时器的方法是使用clearInterval()方法,并传递给它在调用setInterval()时返回的ID/值。