I am trying to make a start a timer clock MM:SS after a certain given interval on page.
I have tried setinterval function but the time it is showing resets after 3 seconds......i wanted it to be call the function only once so the internal function "TIMER CLOCK" keeps going on
setInterval(function timerx(){
var timer = setInterval(clock, 1000);
var msec = 00;
var sec = 00;
var min = 00;
function clock() {
msec += 1;
if (msec == 60) {
sec += 1;
msec = 00;
if (sec == 60) {
sec = 00;
min += 1;
if (sec % 2 == 0) {
alert("Pair");
}
}
}
document.getElementById("timer").innerHTML = min + ":" + sec + ":" + msec;
}
}, 3000); //3000 value could be change
Its like i have a certain amount of time suppose 5 minutes or 300 seconds
i want the timer to be started after 300 seconds and keep on going
Change the outer setInterval() to setTimeout(). The outer timeout only has run one time per your question. That is what setTimeout() is designed to do.
Related
I am trying to add a countdown timer to my Shopify checkout using Google Optimize. I got this to work using the following HMTL & JS. Taken from here
However once the timer finishes and I reload the page it starts from 17 seconds instead of 5 minutes.
Is there a way to get this to repeat the timer from 5 minutes once it hits 0?
document.getElementById('timer').innerHTML =
05 + ":" + 00;
startTimer();
function startTimer() {
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m<0){
return
}
document.getElementById('timer').innerHTML =
m + ":" + s;
console.log(m)
setTimeout(startTimer, 1000);
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}; // add zero in front of numbers < 10
if (sec < 0) {sec = "59"};
return sec;
}
<div>Your cart is reserved for <span id="timer"></span></div>
If you could give the answer like you are talking to a complete beginner it would be greatly appreciated.
Looks like I have a lot to learn!
Welcome to StackOverflow. This should help out...
//JAVASCRIPT
startTimer(5); // SPECIFY AMOUNT OF MINUTES OR NO PARAMETER FOR DEFAULT 5
function startTimer(minutes = 5){
var timeout = minutes * 60000;
var ms = timeout;
var interval = setInterval(function(){
ms -= 1000;
if(ms >= 0) {
var d = new Date(1000*Math.round(ms/1000));
document.getElementById('timer').innerHTML = getMS(d);
} else {
startTimer(5); // MAKE TIMER RESTART AGAIN FOR 5 MINS
// clearInterval(interval); // TO MAKE TIMER STOP UPON REACHING 0:00
}
}, 1000);
}
function getMS(d){
return pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
}
function pad(i) {
return ('0'+i).slice(-2);
}
<!--HTML -->
<body>
<div>Your cart is reserved for <span id="timer"></span></div>
</body>
In javascript the setInterval function allow you to make anything you want every fixed ms.
interval = setInterval(() => {
console.log('Waited for 5m');
// Do whatever you want
console.log('Waiting for 5m again...');
}, 300000);
// To stop the interval
clearInterval(interval);
// This timer keeps reseting back to 2:00 after it reaches 1 minute. Also i do not get a notification that says times up at the right time. Can someone please correct the code. Also the stop/resume timer button also has to stay functional.
var isRunning = false;
var ticker; //this will hold our setTimeout
var seconds,
minutes;
function countdown(mins, secs) {
//i made these global, so we can restart the timer later
seconds = secs || 60; //if user put in a number of minutes, use that. Otherwise, use 60
minutes = mins;
console.log('time stuff',mins,secs,minutes,seconds)
function tick() {
var counter = document.getElementById("timer");
var current_minutes = mins - 1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
if (seconds < 1 && minutes) {
//seconds reached 0, and still minutes left;
seconds=60;
minutes--;
}
if ((seconds > 0 || minutes > 0) && isRunning) {
ticker = setTimeout(tick, 1000);
} else if(isRunning){
console.log(seconds,minutes,isRunning)
alert('Time\'s up, brah!')
}
}
tick();
}
function timeToggle() {
isRunning = !isRunning; //if it's false, set it true. If it's true, set it false.
if (!isRunning) {
clearTimeout(ticker); //or whatever else you set the initial timeOut to.
} else {
//not running! and time is defined;
var sec = seconds||60;
console.log('def!',minutes, sec)
countdown(minutes, sec);
}
}
isRunning = true;
countdown(2);
<div id="timer">2:00</div>
<button onclick="timeToggle()">Stop time</button>
There is a small flaw in your logic.
During the countdown initialization your doing
seconds = secs || 60;
Which effectively add 60 seconds to the time you want if you don't initialize the seconds. see:
function countdownInit(mins, secs) {
seconds = secs || 60;
minutes = mins;
console.log(mins + 'min ' + seconds + 'sec');
}
countdownInit(1, 30) // ok
// 1min 30sec
countdownInit(1) // not ok
// 1min 60sec
// thats 2 minutes
The second issue here is that you use a var current_minutes that equals minutes - 1 to display the time. So you are not showing the real counter.
the fix is as follow:
function countdown(mins, secs) {
seconds = secs;
minutes = mins;
// if secs is 0 or uninitialized we set seconds to 60 and decrement the minutes
if(!secs) {
minutes--;
seconds = 60;
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
// we use minutes instead of current_minutes in order to show what's really in our variables
counter.innerHTML =
minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
// rest of code
}
// rest of code
}
I tried to keep as much as your code as possible.
Hello my countdown not Stop at zero i need to change my test when countdown going to zero, This countdown start again after zero value i need to replace value after countdown is zero ..... $countdown = 50
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
// get the number of seconds that have elapsed since
// startTimer() was called
diff = duration - (((Date.now() - start) / 1000) | 0);
// does the same job as parseInt truncates the float
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
// add one second so that the count down starts at the full duration
// example 05:00 not 04:59
start = Date.now() + 1000;
}
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fiveMinutes = <?php echo $countdown?>
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
PHP In body
if ($countdown>3){
echo "Next Submit: Wait <span id='time'></span>";
}else{
echo "Next Submit: READY....!";
}
You should save the setInterval() call to a variable.
var myTimer = setInterval();
This way you can reference it later. Then, you can have a call within your function to check for a certain condition (in your case when the countdown reaches 0) and then use clearInterval() to end the timer.
Topic covering clearInterval()
I am trying to make a timer using JavaScript. The problem is, I can't get the timer to stop when it reaches 0. I have tried using return and if statements, but nothing seems to be working. Am I on the right track, or is there a better way to do this?
<input type="text" id="minutes" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<span>:</span>
<input type="text" id="seconds" style="width:30px;text-align:center" maxlength="2" placeholder="00">
<button onclick="timer()">Set</button>
<script>
//This prototype correctly uses the modulus function when dealing with negative numbers.
Number.prototype.mod = function (m) {
return ((this % m) + m) % m
}
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
var initial = seconds * 1000 //Amount of seconds (converted to milliseconds) initially set.
var milliseconds = (minutes * 60000) + (seconds * 1000) //Total amount of milliseconds set.
setTimeout(function () {
alert("Time's up!")
}, milliseconds) //Display a message when the set time is up.
/*\Decreases the minute by one after the initially set amount of seconds have passed.
|*|Then, clears the interval and sets a new one to decrease the minute every 60 seconds.
\*/
test = setInterval(function () {
minutes--;
document.getElementById('minutes').value = minutes;
clearInterval(test)
setInterval(function () {
minutes--;
document.getElementById('minutes').value = minutes
}, 60000)
}, initial)
//Seconds are set to decrease by one every 1000 milliseconds, then be displayed in the seconds box.
setInterval(function () {
seconds--;
document.getElementById('seconds').value = seconds.mod(60)
}, 1000)
}
You have four different timer functions (setTimer and two setIntervals) when you only need one. JSFiddle
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
var intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
}
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
if (minutes == 0 && seconds == 0) {
alert("Time's up!");
clearInterval(intervalTimer);
}
}, 1000);
}
In general, you need to make sure every setInterval is given a name (var x = setInterval...) and cleared later on (clearInterval(x)). You could have separate timers (one for the minutes which starts after the given number of seconds then repeats every 60 seconds, one for seconds, and one to display the message) if you really want to for some reason, as long as you clear all of the interval timers once the countdown reaches zero.
Using two timers might make sense, however. This would make sure that the Time's up message really appears when it's supposed to, even if there is any imprecision in the interval timer.
function timer() {
var minutes = document.getElementById('minutes').value,
seconds = document.getElementById('seconds').value,
intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds = 59;
minutes--;
}
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
}, 1000);
setTimer(function () {
alert("Time's up!");
clearInterval(intervalTimer);
}, minutes * 60000 + seconds * 1000);
}
I made improvements to Stuart's answer: fiddle
Basically the same thing, except it works properly:
function clearTimer() {
clearInterval(intervalTimer);
}
var intervalTimer;
function timer() {
var minutes = document.getElementById('minutes').value //Value of minutes box.
var seconds = document.getElementById('seconds').value //Value of seconds box.
intervalTimer = setInterval(function () {
seconds--;
if (seconds < 0) {
seconds += 60;
minutes--;
}
if (minutes < 0) {
alert("Time's up!");
clearTimer();
} else {
document.getElementById('minutes').value = minutes;
document.getElementById('seconds').value = seconds;
}
}, 1000);
}
Im not a great javascript guy, but maybe this will help. i made this in typescript http://www.typescriptlang.org/Playground/
but i would do timing different and use the javascript date object and calculate differences. This is a simple example of how i would start to create a time (without the date object)
javascript
var Timer = (function () {
function Timer(time) {
this.accuracy = 1000;
this.time = time;
}
Timer.prototype.run = function (button) {
var _this = this;
this.time -= 1; //this is inaccurate, for accurate time use the date objects and calculate the difference.
//http://www.w3schools.com/js/js_obj_date.asp
button.textContent = this.time.toString();
if (this.time > 0) {
setTimeout(function () {
return _this.run(button);
}, 1000);
}
};
return Timer;
})();
var time = new Timer(10);
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);
typescript(in case you wonder)
class Timer {
accuracy = 1000;//update every second
time: number;
constructor(time: number) {
this.time = time;
}
run(button: HTMLButtonElement) {
this.time -=1;//this is inaccurate, for accurate time use the date objects and calculate the difference.
//http://www.w3schools.com/js/js_obj_date.asp
button.textContent = this.time.toString();
if(this.time > 0)
{
setTimeout(()=> this.run(button),1000);
}
}
}
var time = new Timer(10)
var button = document.createElement('button');
time.run(button);
document.body.appendChild(button);
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
var interval = setInterval(function() {
var el = document.getElementById(element);
// if the time is 0 then end the counter
if(time == 0) {
//el.innerHTML = "countdown's over!";
// document.getElementById("timer").style.visibility="hidden";
clearInterval(interval);
return;
}
var hour=Math.floor( time / (60*60) );
if (hour < 10) hour = "0" + hour;
var minutes = 0;
if(time>=60 && hour>0)
minutes=Math.floor( (time / 60 )-60);
else{
minutes=Math.floor( (time / 60 ));
}
if (minutes < 10) minutes = "0" + minutes;
var seconds = time % 60;
if (seconds < 10) seconds = "0" + seconds;
// var text = hour+":"+minutes; //+ ':' + seconds;
var text = minutes; //+ ':' + seconds;
el.innerHTML = text;
time--;
}, 1000);
}
when i am calling the method 2wice, its creating flickering effect.
i.e. countdown(element, 50, 0);
it count downs but if i call it again i.e. countdown(element, 35, 0); it is flicks showing both the countddowns
You need to cancel the interval when the plugin initializes if you are going to call it on the same element. Otherwise you are running two intervals at once.
I'd suggest returning the interval from your function and allowing yourself to pass that interval in as a parameter. That way you can always cancel the interval before starting it (in case there is already one going). If you pass null for the interval var, you can still run clearInterval() without throwing errors.
For example:
function countdown(element, minutes, seconds, interval) {
// set time for the particular countdown
var time = minutes*60 + seconds;
clearInterval(interval);
return setInterval(function() {
...
Your first call could be:
var savedInterval = countdown('some-ele-id', 1, 1, null);
And your second call could be:
var interval = countdown('some-ele-id', 1, 1, savedInterval);
Another solution would be to save the interval as a global variable and cancel it without passing it as a parameter inside your plugin.
An alternative to avoid modify your code is:
var interval;
...
function countdown(element, minutes, seconds) {
// set time for the particular countdown
var time = minutes*60 + seconds;
interval = setInterval(function() {
...
And in your second call:
clearInterval(interval);
countdown(element, 35, 0);