Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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() {
}
like image 495
Shaggy Avatar asked Aug 10 '12 11:08

Shaggy


People also ask

How do you call a function after some time in node JS?

Actually setTimeout() does exactly what you are asking for, it does not block and will execute the given function at some time in the future.

Which timing function in JavaScript calls the given function only once after a specific time interval?

setTimeout allows us to run a function once after the interval of time.

Can JavaScript function run after delay?

Use setTimeout() inbuilt function to run function after a delay in JavaScript. It's plain JavaScript, this will call your_func once, after fixed seconds (time).

How do you call a function repeatedly after a fixed time interval in jquery?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.


5 Answers

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
like image 143
Akash KC Avatar answered Sep 22 '22 22:09

Akash KC


Execute function FetchData() once after 1000 milliseconds:

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

Execute function FetchData() repeatedly every 1000 milliseconds:

setInterval( FetchData, 1000);
like image 21
Mark Avatar answered Sep 20 '22 22:09

Mark


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)
like image 42
Jakub Avatar answered Sep 21 '22 22:09

Jakub


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.

like image 43
oezi Avatar answered Sep 20 '22 22:09

oezi


Timeout:

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

Interval:

setInterval(() => {
   console.log('Hello Interval!')
}, 2000);
like image 24
DevonDahon Avatar answered Sep 22 '22 22:09

DevonDahon