JavaScript: get code to run every minute
Using setInterval:
setInterval(function() {
// your code goes here...
}, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() {
// your code goes here...
}, 60 * 1000);
clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() {
// runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);
call function on the minute every minute
Timers and javascript times aren't very accurate, and I would think the only way to make sure a function is executed every whole minute over time, is to check the seconds every second
setInterval(function() {
if ( new Date().getSeconds() === 0 ) onTheMinFunc();
},1000);
FIDDLE
Checking setInterval every 5 minutes on the 0 second
You should find out what's the time to your next rounded 5 min. like this:
const FIVE_MIN = 1000 * 60 * 5;
function waitAndDoSomething() {
const msToNextRounded5Min = FIVE_MIN - (Date.now() % FIVE_MIN);
console.log(`Waiting ${msToNextRounded5Min}ms. to next rounded 5Min.`);
setTimeout(() => {
console.log('It is now rounded 5 min');
waitAndDoSomething();
}, msToNextRounded5Min);
}
waitAndDoSomething();
Calling a function every 60 seconds
If you don't care if the code within the timer
may take longer than your interval, use setInterval()
:
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout
along with a self-executing anonymous
function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee
in this example as function reference. It's a better way to give the function a name and call that within setTimeout
because arguments.callee
is deprecated in ecmascript 5.
Want a javascript function to run every minute, but max 3 times
Like this:
var runCount = 0;
function timerMethod() {
runCount++;
if(runCount > 3) clearInterval(timerId);
//...
}
var timerId = setInterval(timerMethod, 60000); //60,000 milliseconds
Run JS function every new minute
When the user logs in, get the current time and seconds of the minute, subtract 60
to get the remaining seconds, then multiply to set the timer
var time = new Date(),
secondsRemaining = (60 - time.getSeconds()) * 1000;
setTimeout(function() {
setInterval(update, 60000);
}, secondsRemaining);
How would I get this code to update every minute?
Need something that will continue on instead of a one and done function so using setInterval(function(),1000); below works as shown in https://www.w3schools.com/howto/howto_js_countdown.asp
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
</head>
<body>
<div id="popup-content">
<h6 id=title></h6>
<p>Enter the time(in minutes) you want to spend on this page: </p>
<input type="number" name="quantity" min="1" max="60" id="textBox">
<button onclick="ductivity()" id="set">Set Timer</button>
Time Left: <p id="timeLeft"></p>
</div>
<script>
function ductivity(){
let start=Date.now();
let interval = setInterval(function() {
let x = document.getElementById("textBox").value;
let elapsed = (Date.now() - start)/1000;//time elapsed in seconds
let y = Math.floor((x * 60) - elapsed);
if(y>=0){
document.getElementById("timeLeft").innerHTML = "Seconds Left:" + y;
}
else{
document.getElementById("timeLeft").innerHTML = "TIMES UP";
}
},1000);
}
</script>
</body>
</html>
Creating a loop using setTimeout up to the minute, then every five minutes
A completely different approach, since this seems like an XY problem, is to just have an interval for every minute, check if it's a multiple of 5, if so do something, otherwise just break out of the function. (As suggested by @Heretic Monkey)
console.log("Starting...");
const task = () => {
if ((new Date()).getMinutes % 5 !== 0) {
console.log("Not a multiple of 5 minutes");
return; // would just be return; in production code
}
console.log("Do something")
// rest of function...
}
task();
setInterval(task, 1000 * 60);
Related Topics
How to Create Every Combination Possible for the Contents of Two Arrays
Dynamically Using the First Frame as Poster in HTML5 Video
Best Way to Execute Js Only on Specific Page
Html5/JavaScript - Dataurl to Blob & Blob to Dataurl
Javascript: Get Image Dimensions
Show Loading Icon Until the Page Is Load
How to Set Preview of Video File, Selecting from Input Type='File'
Changing the Order of Elements
JavaScript Code Not Work in Head Tag
Onclick Calling Hide-Div Function Not Working
Using Canvas to Animate a Sorting Algorithm in Js
Sending Message to a Specific Connected Users Using Websocket
HTML Drag and Drop on Mobile Devices
JavaScript Regex Returning True.. Then False.. Then True.. etc
How to Tell Google Translate to Not Translate a Section of a Website
How to Disable Div Element and Everything Inside