dadadodo dadadodo - 13 days ago 8
Javascript Question

I need some explanation for some of this code

this a count down timer. I cannot understand how

var timer
works (what is its set value after each interval?) and how timer produces 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);

Answer
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;
Comments