[javascript] Javascript: Call a function after specific time period

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

Here is my function I want to run:

function FetchData() {
}

This question is related to javascript function timer

The answer is


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);

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.


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)

Execute function FetchData() once after 1000 milliseconds:

setTimeout(FetchData,1000);

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval(FetchData,1000);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to timer

Flutter Countdown Timer How to do a timer in Angular 5 Create a simple 10 second countdown Python loop to run for certain amount of seconds Error 1053 the service did not respond to the start or control request in a timely fashion Wait some seconds without blocking UI execution The simplest possible JavaScript countdown timer? How can I perform a short delay in C# without using sleep? How to add a "sleep" or "wait" to my Lua Script? How to use timer in C?