This a count down timer. I don't understand how var timer works. What is its set value after each interval? How does the timer produce the number of minutes and seconds? Could some one break down step-by-step how this bit of code operates?
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
Here is the complete code:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
minutes = parseInt(timer / 60, 10);
Minutes are number of current total seconds divided by 60 (seconds in a minute).
E.g.: 65 / 60 = 1 minute. We just keep the integer part.
seconds = parseInt(timer % 60, 10);
Seconds are calculated as the module 60 of the current total seconds counter.
E.g.: 65 % 60 = 5 (1 minute, 5 seconds)
[Notice that in the second line the parseInt is unnecessary.]
var timer = duration, seconds, minutes;
this can also be written as:
var timer = duration;
var seconds;
var minutes;
You can declare and instialise multiple variables at a time in javascript.
var a,
b,
c;
is same as
var a;
var b;
var c;
also you can intialize variable too so
var timer = duration, seconds, minutes;
is same as writing
var timer = duration;
var seconds;
var minutes;
(as #Lorenzo already mentioned)
var timer = duration, seconds, minutes declares 3 variables with only the first getting initialized. It is the same as writing:
var timer = duration;
var seconds;
var minutes;
Related
I was searching for a sitewide javascript timer, which does not reset when a page is changed, and I have stumbled onto this one, along with its demo.
This could be a stupid question, but I was wondering if this "minutes : seconds" timer format could be turned into an animated progress bar type of countdown, meaning that as the time passes, the bar should get smaller.
Here is the code I am currently using:
<div id="time"></div>
<script>
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + " " + " " + seconds;
if (--timer < 0) {
timer = duration;
}
console.log(parseInt(seconds))
window.localStorage.setItem("seconds",seconds)
window.localStorage.setItem("minutes",minutes)
}, 1000);
}
window.onload = function () {
sec = parseInt(window.localStorage.getItem("seconds"))
min = parseInt(window.localStorage.getItem("minutes"))
if (parseInt(min*sec)) {
var fiveMinutes = (parseInt(min*60)+sec);
} else{
var fiveMinutes = 60 * 45;
}
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
</script>
Any ideas?
I'm very new to Javascript and I found myself stuck with this issue. I want to make this countdown repeat after the time runs out, however I'm not really sure how to do it, and my attempts to make it work failed. Would appreciate help how to do it, Thanks.
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
// here's the problem. not sure how to make it repeat
}
}, 1000);
}
window.onload = function () {
var fiveMinutes = 60 * 5,
display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};
Tried using clearInterval() and setTimeout() but instead of it working the countdown either went past 00:00 (00:0-1 and so on) or just didn't work at all.
You can reset timer:
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
What you're describing is a forever countdown.
Note that eventhough you specify 1000 in the setInterval(). The timer isn't precise, so the callback may fire less than or greater than 1000ms. It is much safer to capture the startTime and then calculate the currentTime when the callback fires and measure the elapsedTime. This will give a true indication of elapsed time regardless of whether the timer is running slow or fast.
Because of the reset requirement. I actually infer that the timer is an infinite loop. We run it forever. There is no description as to when the timer is aborted, so, we just continue measuring currentTime and note elapse.
I use elapsedTime = (currentTime - startTime) / 1000 to calculate the elapsed time in seconds. Then, I elapsed % duration to make the counter stop at the duration and reset. Finally, I flip the math countdown = duration - 1 - (elapsedTime % duration) so instead of counting up, it counts down.
We then break down countdown into the minutes and seconds components.
Below is a fully working example that uses jQuery.
function startTimer(duration, display) {
let startTime = Date.now();
setInterval(function() {
let currentTime = Date.now();
let elapsedTime = Math.floor((currentTime - startTime) / 1000);
let countdown = duration - 1 - (elapsedTime % duration);
let minutes = Math.floor(countdown / 60).toString().padStart(2, "0");
let seconds = (countdown % 60).toString().padStart(2, "0");
display.text(minutes + ":" + seconds);
}, 1000 );
}
let fiveMinutes = 60 * 5;
let display = $("#time");
startTimer(fiveMinutes, display);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label id="time">mm:ss</label>
I have a 5 minutes countdown. This function launch automatically when page load. I want to reload data of page and resetting this countdown. The code looks like this.
HTML
<a onClick="timer()" title="Pincha para actualizar" class="pull-right" id="time"></a>
JS
function timer(){
var timer = 60 * 5, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
The problem: When i click the link the timer goes crazy, doesn´t reset properly.
Anybody knows what´s the rigth way to reset countdown?
You are missing a clearInterval otherwise you are creating a new interval each time you click on the element.
let interval = null;
function timer(){
var timer = 60 * 5, minutes, seconds;
if (interval !== null) {
clearInterval(interval);
}
interval = setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
you can use clearInterval inside setInterval itself
function timer(){
var timer = 60 * 5, minutes, seconds;
interval = setInterval(()=> {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
$('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);
if (--timer < 0) {
timer = duration;
}
if (interval !== null) clearInterval(interval);
}, 1000);
}
I've got a working countdown timer which starts at 30 minutes.
With only 3 minutes left (so after 27 minutes) I'd like the number 250 to decrease at random intervals from 3 minutes left down to the end of the countdown.
Any ideas?
https://codepen.io/anon/pen/bWoGrb
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * 30,
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
Maybe use something like this (I hope I clearly understood the question):
Just using a if/else within the condition something to say: Go normal when more than 60*3, and when under 60*3 seconds rest, there is chance to do nothing
// Stopwatch
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
if(timer > 60*3 || Math.random() < 0.25) {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
timer = duration;
}
} else {
/* do not reduce the timer to wait 1 interval more */
/* or maybe do like `timer -= Math.random()` if you want to reduce it faster */
}
}, 1000);
}
window.onload = function () {
var thirtyMinutes = 60 * /*30*/ 4, // just set to 4 to see faster
display = document.querySelector('#stopwatch');
startTimer(thirtyMinutes, display);
};
<div id='stopwatch'></div>
I've some problem with a string replace, in particular I've a php that return an array, each index of array contains a specific string of translation. So essentially, this array are saved inside: GlobalVariables.language['hello_world'], that for example return Hello world.
Now I've an array index that contains this translation string:
wait $seconds seconds before try again
I set the seconds inside an interval function that working as a countdown:
setInterval(function ()
{
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
text = text.replace('$seconds', seconds);
console.log(text);
$('.alert').text(text);
if (--timer < 0)
{
timer = 0; //Stoppo il timer
}
}, 1000);
this will return a string like this:
wait 20 seconds before try again
but only for the first time, 'cause later the $seconds part of the string is already replaced, I though to replace only digital number of text for second timing, but I can't do this 'cause before call setInterval I append the string to another that contains a digital number.
How can I solve this problem?
dont replace the original variable but use a different one.
text will then always contain $seconds:-
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text2 = text.replace('$seconds', seconds);
console.log(text2);
$('.alert').text(text2);
if (--timer < 0) {
timer = 0; //Stoppo il timer
}
}, 1000);
First time it works as $seconds is found in the string. However next time(2nd iteration onward) since $seconds not exists in the text, thus its not replaced.
You should persist original with element and used it as template.
//Perists original text with element
var alertElem = $('.alert');
alertElem.data('text', text);
setInterval(function (){
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
alertElem.text(function(){
return alertElem.data('text').replace('$seconds', seconds)
});
if (--timer < 0)
{
timer = 0;
}
}, 1000);