I have the following code. It’s a countdown timer and I have to input the start time for the counter. I am wondering how can I make it place a random interval between 30 seconds to 2 minutes for the defaultTimer variable.
$(function() {
var defaultTimer = 25, // Default amount of seconds if url variable is not found
callback = function() {
// Will be executed when the timer finishes
alert("Time!!");
};
var counter = 1, timer,
match = document.location.href.match(/[\?|&]timer=(\d+)/i),
totalTime = match ? match[1] : defaultTimer;
timer = setInterval(function() {
if (totalTime != -1 && !isNaN(totalTime)) {
val = 'Time left: ' + (function() {
var m = Math.floor(totalTime / 60);
if (m < 10) {
return '0'.concat(m);
} else {
return m;
}
})() + ':' + (function() {
var s = totalTime % 60;
if (s < 10) {
return '0'.concat(s);
} else {
return s;
}
})();
$('#counter').html(val);
totalTime--;
} else {
window.clearInterval(timer);
timer = null;
callback();
}
}, 1000);
});
Math.random()will give you a random number between 0 and 1. If you want to make that between 30 and 120: