[javascript] Calling a function every 60 seconds

Using setTimeout() it is possible to launch a function at a specified time:

setTimeout(function, 60000);

But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let's say).

This question is related to javascript function timer setinterval

The answer is


A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {

}

var timer = setInterval(myTimer, 5000);

call this line to stop the loop:

clearInterval(timer);

use the

setInterval(function, 60000);

EDIT : (In case if you want to stop the clock after it is started)

Script section

<script>
var int=self.setInterval(function, 60000);
</script>

and HTML Code

<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>

In jQuery you can do like this.

_x000D_
_x000D_
function random_no(){_x000D_
     var ran=Math.random();_x000D_
     jQuery('#random_no_container').html(ran);_x000D_
}_x000D_
           _x000D_
window.setInterval(function(){_x000D_
       /// call your function here_x000D_
      random_no();_x000D_
}, 6000);  // Change Interval here to test. For eg: 5000 for 5 sec
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="random_no_container">_x000D_
      Hello. Here you can see random numbers after every 6 sec_x000D_
</div>
_x000D_
_x000D_
_x000D_


// example:
// checkEach(1000, () => {
//   if(!canIDoWorkNow()) {
//     return true // try again after 1 second
//   }
//
//   doWork()
// })
export function checkEach(milliseconds, fn) {
  const timer = setInterval(
    () => {
      try {
        const retry = fn()

        if (retry !== true) {
          clearInterval(timer)
        }
      } catch (e) {
        clearInterval(timer)

        throw e
      }
    },
    milliseconds
  )
}

A better use of jAndy's answer to implement a polling function that polls every interval seconds, and ends after timeout seconds.

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000;

    (function p() {
        fn();
        if (((new Date).getTime() - startTime ) <= timeout)  {
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

UPDATE

As per the comment, updating it for the ability of the passed function to stop the polling:

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000,
    canPoll = true;

    (function p() {
        canPoll = ((new Date).getTime() - startTime ) <= timeout;
        if (!fn() && canPoll)  { // ensures the function exucutes
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

function sendHeartBeat(params) {
    ...
    ...
    if (receivedData) {
        // no need to execute further
        return true; // or false, change the IIFE inside condition accordingly.
    }
}

here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()

var count = 0;
function abc(){
    count ++;
    console.log(count);
}
setInterval(abc,60*1000);

You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,

function multiStep() {
  // do some work here
  blah_blah_whatever();
  var newtime = 60000;
  if (!requestStop) {
    setTimeout(multiStep, newtime);
  }
}

There are 2 ways to call-

  1. setInterval(function (){ functionName();}, 60000);

  2. setInterval(functionName, 60000);

above function will call on every 60 seconds.


_x000D_
_x000D_
function random(number) {_x000D_
  return Math.floor(Math.random() * (number+1));_x000D_
}_x000D_
setInterval(() => {_x000D_
    const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';//rgb value (0-255,0-255,0-255)_x000D_
    document.body.style.backgroundColor = rndCol;   _x000D_
}, 1000);
_x000D_
<script src="test.js"></script>_x000D_
it changes background color in every 1 second (written as 1000 in JS)
_x000D_
_x000D_
_x000D_



setInterval(fn,time)

is the method you're after.


Call a Javascript function every 2 second continuously for 10 second.

_x000D_
_x000D_
var intervalPromise;_x000D_
$scope.startTimer = function(fn, delay, timeoutTime) {_x000D_
    intervalPromise = $interval(function() {_x000D_
        fn();_x000D_
        var currentTime = new Date().getTime() - $scope.startTime;_x000D_
        if (currentTime > timeoutTime){_x000D_
            $interval.cancel(intervalPromise);_x000D_
          }                  _x000D_
    }, delay);_x000D_
};_x000D_
_x000D_
$scope.startTimer(hello, 2000, 10000);_x000D_
_x000D_
hello(){_x000D_
  console.log("hello");_x000D_
}
_x000D_
_x000D_
_x000D_


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?

Examples related to setinterval

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead? How can I pause setInterval() functions? Can clearInterval() be called inside setInterval()? Stop setInterval clearInterval() not working Calculating Page Load Time In JavaScript Javascript setInterval not working How to start and stop/pause setInterval? How do I reset the setInterval timer? jquery function setInterval