I am making a online quiz system and i want to convert my timer from seconds to minutes and seconds. Please help me to solve this problem here is my code
<div id="divCounter"></div>
<script type="text/javascript">
if(localStorage.getItem("counter")){
if(localStorage.getItem("counter") <= 0){
var value = 110;
}
else{
var value = localStorage.getItem("counter");
}
}
else{
var value = 10;
}
var counter = function (){
document.getElementById('divCounter').innerHTML = localStorage.getItem("counter");
if(value <= 0){
window.location="http://www.google.com"
}else{
value = parseInt(value)-1;
localStorage.setItem("counter", value);
}
};
var interval = setInterval(function (){counter(value);}, 1000);
Try something like this:
function convert(value) {
return Math.floor(value / 60) + ":" + (value % 60 ? value % 60 : '00')
}
DEMO
value/60 + ":" + value%60, formats to (m)m:ss figure out the right padding
I would suggest you simply use this function (taken from here) which transforms a number of seconds into an string representing the hours, minutes and seconds in format HH:MM:SS:
function secondsToTimeString(seconds) {
var minutes = 0, hours = 0;
if (seconds / 60 > 0) {
minutes = parseInt(seconds / 60, 10);
seconds = seconds % 60;
}
if (minutes / 60 > 0) {
hours = parseInt(minutes / 60, 10);
minutes = minutes % 60;
}
return ('0' + hours).slice(-2) + ':' + ('0' + minutes).slice(-2) + ':' + ('0' + seconds).slice(-2);
}
Related
Well my code should be working but it isn't. Each time I reload the time, my Countdown start back at his initialised value.
Since I'm not familliar with JS you may be able to m'éclaircir the mind
<script>
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()',1000,function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
});
</script>
How do I call it
<h1>Server Release in : <span id="countdown" class="timer"></span></h1>
I just want my timer to not refresh each time you reload the page.
Any kind of help would be appreciated
Here you go.
var upgradeTime = 172801; //Timer length in ms
var timerMS = window.localStorage.getItem("date");
startTimer();
function timer() {
var difference = timerMS - Date.now();
if (difference <= 0) {
startTimer();
return;
}
var seconds = (difference / 1000).toFixed(0),
days = Math.floor(seconds / 24 / 60 / 60),
hoursLeft = Math.floor((seconds) - (days * 86400)),
hours = Math.floor(hoursLeft / 3600),
minutesLeft = Math.floor((hoursLeft) - (hours * 3600)),
minutes = Math.floor(minutesLeft / 60),
remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
setTimeout(timer, 1000);
}
function startTimer() {
if (!timerMS || timerMS < Date.now()) {
timerMS = Date.now() + upgradeTime;
window.localStorage.setItem("date", timerMS);
}
timer();
}
Hi everybody I’ve tried (and failed) to change this simple jquery code to countdown 24 hours instead of the current 1 hour. I have a function called getMinutesUntilNextHour() that should calculate and display the 24 hour countdown:
function getMinutesUntilNextHour() {
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
if (cur_secs == 60) {
cur_mins = cur_mins;
cur_secs = 0;
} else {
cur_mins = cur_mins - 1;
}
if(secs > 50){
var response = (cur_mins) + ":0" + (cur_secs);
} else if(cur_secs == 0) {
var response = (cur_mins) + ":00";
} else {
var response = (cur_mins) + ":" + (cur_secs);
}
jQuery('#time_till_hour').text(function(){
return response;
});
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
I added now.getHours() then cur_hours = 24 - hours but it doesn’t display correctly. Should I add something to if current hours = 0 section?
Thanks in advance for any help you may be able to offer
Perhaps you could adjust and simplify your getMinutesUntilNextHour() function in the following way:
function getMinutesUntilNextHour() {
var now = new Date();
var hours = now.getHours();
var mins = now.getMinutes();
var secs = now.getSeconds();
// Compute time remaining per unit
var cur_hours = 23 - hours;
var cur_mins = 60 - mins;
var cur_secs = 60 - secs;
// Correct zero padding of hours if needed
if(cur_hours < 10) {
cur_hours = '0' + cur_hours;
}
// Correct zero padding of minutes if needed
if(cur_mins < 10) {
cur_mins = '0' + cur_mins;
}
// Correct zero padding of seconds if needed
if(cur_secs < 10) {
cur_secs = '0' + cur_secs;
}
// Format the countdown string
var response = cur_hours + ':' + cur_mins + ':' + cur_secs;
jQuery('#time_till_hour').text(response);
setTimeout(getMinutesUntilNextHour, 1000);
}
getMinutesUntilNextHour();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="time_till_hour">
</div>
Hope that helps!
I've been working on showing user's how long they spent on a certain page. I think I may have over complicated it. Currently I am showing them the number of minutes and then showing them the number of seconds. This almost works except when its at two minutes 5 seconds for example it looks like this: 2:5 instead of 2:05. Then once it hits 10 seconds its fine: 2:10.
Any idea how I'd change my code to correct this? Thanks!
var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();
function getTimeSpentOnSite(){
timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
return timeSpentOnSite;
}
function startCounting(){
timerStart = Date.now();
timer = setInterval(function(){
timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
$("#timeSpentMin").html(parseInt(timeSpentOnSite/1000 / 60));
$("#timeSpentSec").html(parseInt(timeSpentOnSite/1000 % 60));
},1000);
}
startCounting();
You can use this simple function:
function padTime(time) {
return ("0" + time).slice(-2);
}
Pass it any time portion you want and it will pad it for you:
var min = 5;
var sec = 2;
console.log("Unpadded: " + min + ":" + sec);
console.log("Padded seconds: " + min + ":" + padTime(sec));
console.log("Padded minutes & seconds: " + padTime(min) + ":" + padTime(sec));
min = 12;
sec = 52;
console.log("Unpadded: " + min + ":" + sec);
console.log("Padded seconds: " + min + ":" + padTime(sec));
console.log("Padded minutes & seconds: " + padTime(min) + ":" + padTime(sec));
function padTime(time) {
return ("0" + time).slice(-2);
}
A simple padding of the values less than 10 could do the trick. So something like the following
function padValue(value) {
if (value < 10) {
return '0' + value;
}
return value;
}
And then for the minutes value, you can write it as follows:
$("#timeSpentSec").html( padValue(parseInt(timeSpentOnSite/1000 % 60)) );
change your function to the following , check for the number of digits in the seconds and mins section by converting them with toString() and callin .length see below
function startCounting() {
timerStart = Date.now();
timer = setInterval(function() {
timeSpentOnSite = getTimeSpentOnSite() + (Date.now() - timerStart);
localStorage.setItem('timeSpentOnSite', timeSpentOnSite);
timerStart = parseInt(Date.now());
// Convert to seconds
let sec = parseInt(timeSpentOnSite / 1000 % 60);
sec = sec.toString().length < 2 ? '0' + sec : sec;
let min = parseInt(timeSpentOnSite / 1000 / 60);
min = min.toString().length < 2 ? '0' + min : min;
$("#timeSpentMin").html(min);
$("#timeSpentSec").html(sec);
}, 1000);
}
To pad a number in JavaScript, you can use the built-in padStart method. You can use the function below to return a formatted string, given integer parameters (if you're passing in strings, you can ignore the toString() call).
function formatTime(hour, minute) {
return `${hour}:${minute.toString().padStart(2, '0')}`;
}
I want a jQuery function similar to countTo or a pure javascript function to count to starting to (seconds or decimal time)... and output days HH:MM:SS
convert_seconds(2681623) => output "31D 00:53:43"
or decimal Hours
convert_decimalHours(25.555) => output "1D 01:33:18" (I think Its not correct but is something like that kkkkk)
I prefer seconds to be more accurate and easier to manipulate...
here is something that I Tried...
http://jsfiddle.net/5LWgN/105/
and must be a live counter 1 by 1 seconds counting
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '2681623';
var counter = setInterval(timer, 1000);
function timer() {
console.log(count);
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) + 1).toString();
$('#timer').html(temp);
}
You have some errors in the conversion step, and someone has asked before, see here.
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;
var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds < 10 ? "0" + seconds : seconds);
I have been looking for a count down timer on google and can't seem to find one.
I was just wondering if anyone would be able to help.
I got given one but it displays the wrong times.
I want it to display days, hours, minutes and seconds left.
heres what I need the timer on
http://pastebin.com/fQjyRFXw
It already has the timer code there but it's all wrong, any help would be great, thank you
If it's helps here's a snippet of the Java code
var count = <?= $time['a_time'] ?>;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
minutes %= 60;
hours %= 60;
document.getElementById("clock").innerHTML = hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Ok I see your problem. The a_time stored in database is an Unix timestamp, thus when you are counting down, you need to know how long is between now and a_time instead of only a_time.
Try this:
var count = <?= $time['a_time'] ?>;
var now = Math.floor(new Date().getTime() / 1000);
count = count - now;
var counter = setInterval(timer, 1000); //1000 will* run it every 1 second
function timer() {
count = count - 1;
if(count == -1) {
clearInterval(counter);
return;
}
var seconds = count % 60;
var minutes = Math.floor(count / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
minutes %= 60;
hours %= 24;
document.getElementById("clock").innerHTML = days + "days " + hours + "hours " + minutes + "minutes and " + seconds + " seconds left";
}
Why not use one of the man examples on codepen such as this beautiful one
http://codepen.io/anon/pen/VeLWdz ?
(function (e) {
e.fn.countdown = function (t, n) {
function i() {
eventDate = Date.parse(r.date) / 1e3;
currentDate = Math.floor(e.now() / 1e3);
if (eventDate <= currentDate) {
n.call(this);
clearInterval(interval)
}
seconds = eventDate - currentDate;
days = Math.floor(seconds / 86400);
seconds -= days * 60 * 60 * 24;
hours = Math.floor(seconds / 3600);
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
days == 1 ? thisEl.find(".timeRefDays").text("day") : thisEl.find(".timeRefDays").text("days");
hours == 1 ? thisEl.find(".timeRefHours").text("hour") : thisEl.find(".timeRefHours").text("hours");
minutes == 1 ? thisEl.find(".timeRefMinutes").text("minute") : thisEl.find(".timeRefMinutes").text("minutes");
seconds == 1 ? thisEl.find(".timeRefSeconds").text("second") : thisEl.find(".timeRefSeconds").text("seconds");
if (r["format"] == "on") {
days = String(days).length >= 2 ? days : "0" + days;
hours = String(hours).length >= 2 ? hours : "0" + hours;
minutes = String(minutes).length >= 2 ? minutes : "0" + minutes;
seconds = String(seconds).length >= 2 ? seconds : "0" + seconds
}
if (!isNaN(eventDate)) {
thisEl.find(".days").text(days);
thisEl.find(".hours").text(hours);
thisEl.find(".minutes").text(minutes);
thisEl.find(".seconds").text(seconds)
} else {
alert("Invalid date. Example: 30 Tuesday 2013 15:50:00");
clearInterval(interval)
}
}
var thisEl = e(this);
var r = {
date: null,
format: null
};
t && e.extend(r, t);
i();
interval = setInterval(i, 1e3)
}
})(jQuery);
$(document).ready(function () {
function e() {
var e = new Date;
e.setDate(e.getDate() + 60);
dd = e.getDate();
mm = e.getMonth() + 1;
y = e.getFullYear();
futureFormattedDate = mm + "/" + dd + "/" + y;
return futureFormattedDate
}
$("#countdown").countdown({
date: "1 April 2017 09:00:00", // Change this to your desired date to countdown to
format: "on"
});
});