Converting a countdown timer into minutes - javascript

I have created a simple countdown timer, that counts down the total seconds inputted.
http://jsfiddle.net/tmyie/cf3Hd/
However, I am unsure how to turn 3 minutes (the number entered) into seconds with a format like 1:79, 1:78, etc.
$('.click').click(function () {
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount);
var totalAmount = cleanAmount * 60
$('input').val(" ");
var loop, theFunction = function () {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
}
$('p').text(totalAmount);
};
var loop = setInterval(theFunction, 1000);
})
Any help would be great.

This will show the time like 2:59, 2:58, 2:57, and so on...
1:79, 1:78 isn't a valid time, since a minute has 60 seconds.
Here's the fiddle:
$('.click').click(function () {
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount);
var totalAmount = cleanAmount * 60;
$('input').val(" ");
var loop, theFunction = function () {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
}
var minutes = parseInt(totalAmount/60);
var seconds = parseInt(totalAmount%60);
if(seconds < 10)
seconds = "0"+seconds;
$('p').text(minutes + ":" + seconds);
};
var loop = setInterval(theFunction, 1000);
})

try this code
$('.click').click(function () {
var rawAmount = $('input').val().split(':');
var showTime;
var cleanAmount = ((parseInt(rawAmount[0])*60) +parseInt(rawAmount[1]));
$('input').val(" ");
var loop, theFunction = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(loop);
}
var minutes="0";
var seconds ="0";
if(cleanAmount >60){
minutes = parseInt(cleanAmount/60);
seconds = parseInt(cleanAmount%60);
}
else{
seconds = cleanAmount;
minutes ="0";
}
if(seconds<10)
seconds = "0"+seconds;
$('p').text(minutes+':'+seconds);
};
var loop = setInterval(theFunction, 1000);
});

Related

JavaScript Timer pauses on page reload

I am using a JavaScript code for a timer which works fine with the code below, the only problem is when i refresh the page one second loses.
I need the timer to keep running even if i refresh the page.
I tried to get local time setHours(00) nothing changed.
How do I keep timer running ?
function work(x, id, id_p) {
var span = document.getElementsByClassName('data-work');
for (i = 0; i < span.length; i++) {
var totalsum = span[i].dataset.totalwork;
}
var Clock = {
totalSeconds: parseInt(x),
totalSecondsproject: parseInt(totalsum),
start: function () {
var self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function () {
self.totalSeconds += 1;
self.totalSecondsproject += 1;
var hour = pad(Math.floor(self.totalSecondsproject / 3600));
var min = pad(Math.floor(self.totalSecondsproject / 60 % 60));
var sec = pad(parseInt(self.totalSecondsproject % 60));
var totat_work = hour + ":" + min + ":" + sec;
var totat_work_db = self.totalSeconds;
$(".totatl_hour_work").text(totat_work);
$.ajax({
type: 'Post',
url: 'includes/function.php',
data: {divVal: totat_work_db, id_interview: id, id_project:id_p}
});
}, 1000);
}
};
$('.startButton').ready(function () {
Clock.start();
var refresh = setInterval(function () {
$(window).attr('location', 'agent_dashboard.php?autorefresh');
}, 300 * 1000);
});
}

Prevent timer reset on page refresh

I am in trouble. I did countdown timer code in java script but when I refresh the page timer is reset so how to fix this problem
Here is my code.
var min = 1;
var sec = 59;
var timer;
var timeon = 0;
function ActivateTimer() {
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = min + ":" + sec;
document.getElementById("Label1").innerHTML = _time;
if (_time != "0:0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
} else {
window.location.href = "page2.html";
}
}
<BODY onload="Timer();">
<div id="Label1"> </div>
</BODY>
This approach uses localStorage and does not Pause or Reset the timer on page refresh.
<p id="demo"></p>
<script>
var time = 30; // This is the time allowed
var saved_countdown = localStorage.getItem('saved_countdown');
if(saved_countdown == null) {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time + 2) * 1000;
time = new_countdown;
localStorage.setItem('saved_countdown', new_countdown);
} else {
time = saved_countdown;
}
// Update the count down every 1 second
var x = setInterval(() => {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the allowed time
var distance = time - now;
// Time counter
var counter = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = counter + " s";
// If the count down is over, write some text
if (counter <= 0) {
clearInterval(x);
localStorage.removeItem('saved_countdown');
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
Javascript is client-sided. It will reset on reload or any other thing.
A simple solution to your problem might be html5 storage, or session storage.
https://www.w3schools.com/html/html5_webstorage.asp
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Hope this helped!
You're looking for window.localStorage. Something like this should work:
<script language="javascript" type="text/javascript">
var min = 1;
var sec = 59;
var timer;
var timeon = 0;
function ActivateTimer() {
//Don't activate if we've elapsed.
if(window.localStorage.getItem('elapsed') != null)
return;
if (!timeon) {
timeon = 1;
Timer();
}
}
function Timer() {
var _time = min + ":" + sec;
document.getElementById("Label1").innerHTML =_time;
if (_time != "0:0") {
if (sec == 0) {
min = min - 1;
sec = 59;
} else {
sec = sec - 1;
}
timer = setTimeout("Timer()", 1000);
}
else {
window.localStorage.setItem('elapsed', true);
window.location.href = "page2.html";
}
}
</script>

timer implementation in javascript

I had written following code for implementing a timer in JS. But the issue is, for the subsequent recursive calls, the method throws reference error for timeChkSplitTime. How does it happen as its being passed in settimeout().
Also, later I used the easy timer js lib for this. If possible, pls provide an idea to configure the timer for minutes and seconds alone.
function timeChkold(timeChkSplitTime) {
var min = timeChkSplitTime[0], sec = timeChkSplitTime[1];
if (!(timeChkSplitTime[0]==0 && splitTime[1]==0)) {
var strSec, strMin = "0"+min.toString();
if (sec < 10) strSec = "0"+ sec.toString();
else strSec = sec.toString();
$(".timer-btn time").html(strMin+":"+strSec);
timeChkSplitTime[0]=0;
if (sec > 0) timeChkSplitTime[1]--;
else timeChkSplitTime[1] = 59;
setTimeout( "timeChk(timeChkSplitTime);", 1000);
}
else {
var startBtn = $(".start-btn");
startBtn.html("Start");
startBtn.css( {
"border": "1px solid #56B68B",
"background": "#56B68B",
});
var startTime = "01:00";
$(".timer-btn time").html(startTime);
}
}
setTimeout( "timeChk(timeChkSplitTime);", 1000);
should be
setTimeout( timeChk(timeChkSplitTime), 1000);
Variables aren't parsed through strings, on the line with the code:
setTimeout( "timeChk(timeChkSplitTime);", 1000);
It's literally reading the parameter as the value as the text timeChkSplitTime and not the value of the variable timeChkSplitTime. Other than using a string use a function for setTimeout:
setTimeout( timeChk(timeChkSplitTime), 1000);
your code is a little bit of a spaghetti code. you should seperate your code logic from the view. split them into functions. and most importantly, using setTimeout is not efficient in this case.
var CountdownTimer = function(startTime) {
var timeInSeconds = this.stringToSeconds(startTime);
this.original = timeInSeconds;
this.time = timeInSeconds;
this.running = false;
}
CountdownTimer.prototype.start = function(callback) {
this.running = true;
this.interval = setInterval(function() {
if(this.time < 1) {
this.running = false;
clearInterval(this.interval);
} else {
this.time -= 1;
callback();
}
}.bind(this), 1000);
}
CountdownTimer.prototype.pause = function() {
if(this.running) {
this.running = false;
clearInterval(this.interval);
}
}
CountdownTimer.prototype.restart = function() {
this.time = this.original;
}
CountdownTimer.prototype.stringToSeconds = function(timeSting) {
var timeArray = timeSting.split(':');
var minutes = parseInt(timeArray[0], 10);
var seconds = parseInt(timeArray[1], 10);
var totalSeconds = (minutes*60) + seconds;
return totalSeconds;
}
CountdownTimer.prototype.secondsToStrings = function(timeNumber) {
finalString = '';
var minutes = parseInt(timeNumber/60, 10);
var seconds = timeNumber - (minutes*60);
var minStr = String(minutes);
var secStr = String(seconds);
if(minutes < 10) minStr = "0" + minStr;
if(seconds < 10) secStr = "0" + secStr;
return minStr + ":" + secStr;
}
to run this code you can add the following
var countdownTest = new CountdownTimer("01:15");
countdownTest.start(onEachTick);
function onEachTick() {
var time = countdownTest.secondsToStrings(countdownTest.time);
console.log(time)
}
you can write your custom code in the onEachTick funciton.
you can check if the timer is running by typing countdownTest.running.
you can also restart and pause the timer. now you can customize your views however you want.

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

Countdown Timer is not showing in javascript

I am new in javascript, I want to create a countdown timer with localStorage which starts from given time and end to 00:00:00, but it's not working,
When I am running my code it is showing value "1506".
Here is my code
<script type="text/javascript">
if (localStorage.getItem("counter")) {
var CurrentTime = localStorage.getItem("counter");
}
else {
var Hour = 3;
var Minute = 25;
var Second = 60;
var CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
}
function CountDown() {
document.getElementById('lblDuration').innerHTML = CurrentTime;
Second--;
if (Second == -1) {
Second = 59;
Minute--;
}
if (Minute == -1) {
Minute = 59;
Hour--;
}
localStorage.setItem("counter", CurrentTime);
}
var interval = setInterval(function () { CountDown(); }, 1000);
</script>
you need to declare variables Hour, Minute, Second, CurrentTime out side if else block. In this case they are not in function CountDown() scope.
you are not setting CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString(); after localStorage.setItem("counter", CurrentTime);
var Hour = 3;
var Minute = 25;
var Second = 60;
var CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
function CountDown() {
document.getElementById('lblDuration').innerHTML = CurrentTime;
Second--;
if (Second == -1) {
Second = 59;
Minute--;
}
if (Minute == -1) {
Minute = 59;
Hour--;
}
CurrentTime = Hour.toString() + ":" + Minute.toString() + ":" + Second.toString();
}
setInterval(function () {
CountDown();
}, 1000);
<div id="lblDuration"></div>
When localStorage is available you don set the values for Hour, Minute and Second. So when the countdown function executed it finds Second to be undefined and the statement Second-- converts Second to NaN.
To fix it just initialize the Hour, Minute and Second Variable.
I 've refactored your code a little bit hope it helps:
function CountDown() {
var currentTime = getCurrentTime();
printCurrentTime(currentTime)
currentTime.second--;
if (currentTime.second == -1) {
currentTime.second = 59;
currentTime.minute--;
}
if (currentTime.minute == -1) {
currentTime.minute = 59;
currentTime.hour--;
}
setCurrentTime(currentTime);
}
function setCurrentTime(newCurrentTime){
if(localStorage) localStorage.setItem("counter", JSON.stringify(newCurrentTime));
else setCurrentTime.storage = newCurrentTime;
}
function getCurrentTime(){
var result = localStorage ? localStorage.getItem("counter") : setCurrentTime.storage;
result = result || {hour:3, minute:25, second:60};
if (typeof(result) === "string")result = JSON.parse(result);
result.toString = function(){
return result.hour + ":" + result.minute + ":" + result.second;
}
return result;
}
function printCurrentTime(currentime){
var domTag = document.getElementById('lblDuration');
if(domTag) domTag.innerHTML = currentime.toString();
else console.log(currentime);
}
setInterval(function () { CountDown(); }, 1000);

Categories

Resources