Javascript: Call a function after specific time period

JavascriptFunctionTimer

Javascript Problem Overview


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

Here is my function I want to run:

function FetchData() {
}

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Execute function FetchData() once after 1000 milliseconds:

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

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval( FetchData, 1000);

Solution 3 - Javascript

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)

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

setTimeout(func, 5000);

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShaggyView Question on Stackoverflow
Solution 1 - JavascriptAkash KCView Answer on Stackoverflow
Solution 2 - JavascriptMarkView Answer on Stackoverflow
Solution 3 - JavascriptJakubView Answer on Stackoverflow
Solution 4 - JavascriptoeziView Answer on Stackoverflow
Solution 5 - JavascriptDevonDahonView Answer on Stackoverflow
Solution 6 - JavascriptMaxx Selva KView Answer on Stackoverflow