Javascript: 在特定时间段后调用函数

在 JavaScript 中,如何在特定的时间间隔后调用函数?

下面是我要运行的函数:

function FetchData() {
}
217831 次浏览

sounds like you're looking for setInterval. It's as easy as this:

function FetchData() {
// do something
}
setInterval(FetchData, 60000);

if you only want to call something once, theres setTimeout.

Execute function FetchData() once after 1000 milliseconds:

setTimeout( function() { FetchData(); }, 1000);

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval( FetchData, 1000);

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box every 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

setTimeout(func, 5000);

-- it will call the function named func() after the time specified. here, 5000 milli seconds , i.e) after 5 seconds

Timeout:

setTimeout(() => {
console.log('Hello Timeout!')
}, 3000);

Interval:

setInterval(() => {
console.log('Hello Interval!')
}, 2000);

ECMAScript 6 introduced arrow functions so now the setTimeout() or setInterval() don't have to look like this:

setTimeout(function() { FetchData(); }, 1000)

Instead, you can use annonymous arrow function which looks cleaner, and less confusing:

setTimeout(() => {FetchData();}, 1000)