111

In JavaScript, How can I call a function after a specific time interval?

Here is my function I want to run:

function FetchData() {
}
neophyte
  • 6,540
  • 2
  • 28
  • 43
Shaggy
  • 5,422
  • 28
  • 98
  • 163

6 Answers6

210

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
Stephane
  • 3,173
  • 3
  • 29
  • 42
Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • Be mindful that the sample does NOT give the most exact answer to the question (it answer the question "how can I call a function _every_ specific interval, not _after_ a specific interval – Stephane Apr 22 '21 at 13:46
56

Execute function FetchData() once after 1000 milliseconds:

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

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval( FetchData, 1000);
Mark
  • 6,762
  • 1
  • 33
  • 50
  • 3
    I guess in case of 'setInterval()' the round brackets for the function name i.e. 'FetchData' should not be present because it triggers the function only once. setInterval(FetchData,1000) seems more valid. I tested it in chrome. – Saumil Feb 22 '14 at 18:27
  • 7
    This is incorrect. In the setTimeout the FetchData() will run straight away. You need to wrap it in a function like so : setTimeout(function() { FetchData(); }, 1000); – thatOneGuy Mar 30 '16 at 14:21
9

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)
Jakub
  • 218
  • 3
  • 6
8

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.

oezi
  • 51,017
  • 10
  • 98
  • 115
3

Timeout:

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

Interval:

setInterval(() => {
   console.log('Hello Interval!')
}, 2000);
DevonDahon
  • 7,460
  • 6
  • 69
  • 114
0

setTimeout(func, 5000);

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

Maxx Selva K
  • 454
  • 4
  • 9