Run a Javascript on 1st second of every minute

A very common way to execute a code every minute is something like this:
setInterval(function(){
console.log("Function to execute every minute");
}, 1000*60);

Above code should always work just fine. But what if we want exactly on some particular second ? or as soon as some time has passed.

Below I will show an example where a Javacript code will execute on every 1st second of the minute.
setInterval(function(){
var d = new Date();
if(d.getSeconds() == 0){
console.log("Function to execute every minute");
}
}, 1000);

I am calling the function every second and in that function I am executing the required code only when second is 0 so the code will execute on every 1st second of every minute. Similarly, you can execute a code at any particular time you want.

I wanted a modal to pop-up on every 1st second of a minute as I had implemented a reminder. Worst case scenario was that when page was loaded on 59th second, reminder modal was displayed almost at the end of the minute.

UPDATE 29th Sept 2015:

Never make an ajax call on every particular second of a minute. Apache process will eat up lot of memory on that particular second.

One response to “Run a Javascript on 1st second of every minute”

  1. This article is old. Polling can be avoided by using socket.io(websocket).

    Like

Leave a comment