Trying to code improvement for JS countdown with localStorage - javascript

I'm not enough skilled in js and jq, and think this code looks really bad:
var updateTimerApple = function() {
var timerApple = localStorage.getItem('timerApple');
if ( timerApple < 0 ) {
$(".apple").css("display", "none");
}
else if (timerApple == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
timerApple--;
localStorage.setItem('timerApple', timerApple);
var hours = Math.floor(timerApple / 3600);
var minute = Math.floor((timerApple - (hours * 3600)) / 60);
var second = timerApple - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
var updateTimeroak = function() {
var timeroak = localStorage.getItem('timeroak');
if ( timeroak < 0 ) {
$(".oak").css("display", "none");
}
else if (timeroak == 0) {
$(".oak").html("Oak ok").css("display", "block");;
}
else {
timeroak--;
localStorage.setItem('timeroak', timeroak);
var hours = Math.floor(timeroak / 3600);
var minute = Math.floor((timeroak - (hours * 3600)) / 60);
var second = timeroak - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".oak").html("Oak:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".oak").css("display", "block");
}
};
$(function() {
setInterval(updateTimerApple, 1000);
$(".startApple").click( function() {
localStorage.setItem('timerApple', 51480);
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('timerApple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
$(function() {
setInterval(updateTimeroak, 1000);
$(".startoak").click( function() {
localStorage.setItem('timeroak', 176400);
$(".oak").removeAttr('style');
});
$(".oak").click( function() {
localStorage.removeItem('timeroak');
$(".oak").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
<body>
<div class="content">
<div class="menu">
<button class="startApple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div class="item apple"></div>
<div class="item oak"></div>
</div>
</body>
Or http://jsfiddle.net/38N6x/1/
It works fine, but I am trying to improve it, making it more generic.
Looking for something like this:
function updateTimer(n,t) {
this.n=n;
this.t=localStorage.getItem('n');
if ( t < 0 ) {
$(".apple").css("display", "none");
}
else if (t == 0) {
$(".apple").html("Apple ok").css("display", "block");
}
else {
this.t--;
localStorage.setItem('n', this.t);
var hours = Math.floor(t / 3600);
var minute = Math.floor((t - (hours * 3600)) / 60);
var second = t - (hours * 3600) - (minute * 60);
if (hours < 1) hours = "0" + hours;
if (minute < 10) minute = "0" + minute;
if (second < 10) second = "0" + second;
$(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
$(".apple").css("display", "block");
}
};
$(function() {
setInterval(updateTimer, 1000);
$(".startApple").click( function() {
var apple = new updateTimer ("apple", 23)
$(".apple").removeAttr('style');
});
$(".apple").click( function() {
localStorage.removeItem('apple');
$(".apple").css({"display": "none", "visibility": "hidden","width":"0","height":"0", "padding":"0", "margin":"0"});
});
});
But this code not works. Browser always returns NaN for $(".apple").html("Apple tree:"+" "+hours+"ч"+" "+minute+"м"+" "+second+"с"+" ");
Thx for any help.

After spending some time, i'm found the way for code optimisation.
JS
function catDate(catID, catTime) {
var s = new Date();
s.setSeconds(s.getSeconds() + catTime);
localStorage.setItem(catID, s);
}
function CountDownTimer(dt, id) {
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (dt == 0) {
document.getElementById(id).style.display='none';
return;
}
else if(distance < 0) {
document.getElementById(id).innerHTML = 'Сan collect';
document.getElementById(id).style.display='block';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = days + 'd ';
document.getElementById(id).innerHTML += hours + 'h ';
document.getElementById(id).innerHTML += minutes + 'm ';
document.getElementById(id).innerHTML += seconds + 's ';
document.getElementById(id).style.display='block';
}
timer = setInterval(showRemaining, 1000);
}
CountDownTimer(localStorage.getItem('apple'), 'apple');
CountDownTimer(localStorage.getItem('oak'), 'oak');
$(function() {
$(".startapple").click( function() {
catDate("apple", 5);
});
$("#apple").click( function() {
localStorage.setItem('apple', 0);
});
});
$(function() {
$(".startoak").click( function() {
catDate("oak", 2000);
});
$("#oak").click( function() {
localStorage.removeItem('oak');
});
});
$(function() {
$('div').click( function() {
location.reload();
});
});
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Farm Frenzy</title>
<link rel="stylesheet" media="screen" href="css/style.css"/>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src='js/items.js'></script>
<script type='text/javascript' src='js/itemscall.js'></script>
</head>
<body>
<div class="content">
<div class="menu">
<button class="startapple">Apple</button>
<button class="startoak">Oak</button>
</div>
<div id="apple" class="item"></div>
<div id="oak" class="item"></div>
</body>
</html>
But still have one problem: if user adding new timer (or setting localStorage.setItem('item', 0), for timer hiding), timer shows (or hiding) only after page refresh. Fixed this with
$(function() {
$('div').click( function() {
location.reload();
});
});
But i'm looking for better way.

Related

How to set an alarm in a countdown project while we are using JavaScript?

I am a new learner. I am making a countdown project that gets input from the user and then countdown the time. It rings an alarm after every 5 seconds. But after getting the end-numbers 00:00 it does not stop. It continuously rings the alarm. Please check the code.
<span id="min">00</span>
<span>:</span>
<span id="snd">00</span>
<audio id="myAudio">
<source src="beep-02.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button class="btn" id="start" onclick="timer.start();">START</button>
<span class="mx-3"></span>
<button class="btn" id="set" onclick="location.href='time-selecter.html';">SET</button>
<script type="text/javascript">
var hh = localStorage.getItem("a")
var mm = localStorage.getItem("b")
var ss = localStorage.getItem("c")
function yourfunction() {
document.getElementById("hr").innerHTML = hh;
document.getElementById("min").innerHTML = mm;
document.getElementById("snd").innerHTML = ss;
}
window.onload = yourfunction;
//timer
var start_time = 0;
var elapsed_time = 0;
var requested_time;
var timer_inter;
var timer = {
start: function() {
start_time = new Date();
requested_time = toMs(document.getElementById('hr').innerHTML, document.getElementById('min').innerHTML, document.getElementById('snd').innerHTML, 0);
timer_inter = setInterval(function() {
elapsed_time = new Date() - start_time;
document.getElementById('time').innerHTML = toTimeFormat(requested_time - elapsed_time + 1000, 'hh:mm:ss');
//+ 1000ms because the seconds are rounded down, so without it when the timer SHOWS 00:00:00, it will have to wait 1s before stopping
if (elapsed_time >= requested_time) {
timer.stop();
timer.end();
}
}, 0);
},
stop: function() {
clearInterval(timer_inter);
},
end: function() {
document.getElementById('time').innerHTML = '00:00';
}
};
var x = document.getElementById("myAudio");
function yourFunction(){
setTimeout(yourFunction, 5000);
x.play();
}
function pausefn(){
x.pause();
x.currentTime = 0;
}
$("#start").click(function(){
yourFunction();
});
/*------------------------------*/
/*UTILITY*/
/*------------------------------*/
function toTimeFormat(t, format) {
function addDigit(n) {
return (n < 10 ? '0':'') + n;
}
var ms = t % 1000;
t = (t - ms) / 1000;
var secs = t % 60;
t = (t - secs) / 60;
var mins = t % 60;
var hrs = (t - mins) / 60;
ms = (ms < 10) ? '00' : (ms < 100) ? '0' + Math.floor(ms / 10) : Math.floor(ms / 10);
if (format === 'hh:mm:ss') {
return addDigit(mins) + ':' + addDigit(secs);
} else if (format === 'mm:ss:msms') {
return addDigit(mins) + ':' + addDigit(secs) + ':' + ms;
}
}
function toMs(h, m, s, ms) {
return (ms + s * 1000 + m * 1000 * 60 + h * 1000 * 60 * 60);
}
</script>
I am making a countdown project. I tried to stop an alarm when countdown at 00:00 time. But it countinousily rings the alarm untill I close the browser.

Countdown It does not Work on a minute system

I have a simple code but there is a problem
How do I make this code work in a minute and a second system
Tried but only work a second!
You can look at the code
https://jsfiddle.net/o183pdqg/1/
I hope for help because I am really tired and I am looking for a solution
function secondPassed() {
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
adsElement.style.display = '';
countdownElement.innerHTML = remainingSeconds;
var interval = setInterval(function() {
countdownElement.innerHTML = --remainingSeconds;
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
you need to put variable minutes and seconds within setInterval function to make it work. Convert the time var remainingSeconds = seconds * 1000; from second to milisecond so it will make it easier when working with new Date().getTime().
To get minutes and second, try it using modulus (%) operator to get remaining time from your starting time.
var availability = true
function secondPassed() {
if (!availability) {
return false
}
var seconds = 120;
var countdownElement = document.getElementById('countdown');
var contentElement = document.getElementById('content');
var adsElement = document.getElementById('ads');
availability = false
adsElement.style.display = '';
contentElement.style.display = 'none';
function runInterval () {
var remainingSeconds = seconds * 1000;
let minutes = Math.floor(remainingSeconds % (1000*60*60)/ (1000*60));
let seconds1 = Math.floor(remainingSeconds % (1000*60) / 1000);
if (seconds1 < 10) {
seconds1 = "0" + seconds1;
}
document.getElementById('countdown').innerHTML = minutes + ":" + seconds1;
if (seconds == 0) {
// clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "";
} else {
seconds--;
}
if (remainingSeconds === 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
availability = true
}
}
var interval = setInterval(function() {
// countdownElement.innerHTML = --remainingSeconds;
runInterval ()
}, 1000);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="container">
Send Code
<div id="ads" style="display: none">
<div id="countdown"></div>
<div>Sent!</div>
</div>
<div id="content" style="display: none">Error!</div>
</div>
</body>
</html>
You can try with this answer
secondPassed = () => {
let remainingSeconds = 120;
const countdownElement = document.getElementById('countdown');
const contentElement = document.getElementById('content');
const adsElement = document.getElementById('ads');
adsElement.style.display = '';
const getPad = (num) => {
return (num < 10) ? '0' + num.toString() : num.toString();
}
const interval = setInterval(() => {
let minutes = Math.floor(remainingSeconds / 60) % 60;
let seconds = getPad(remainingSeconds % 60);
countdownElement.innerHTML = `${minutes} : ${seconds}`;
remainingSeconds--;
if (remainingSeconds == 0) {
clearInterval(interval);
contentElement.style.display = '';
adsElement.style.display = 'none';
}
}, 1000);
}

javascript function is not working on button click. But working without button click

In this function, I have implemented a timer which is working fine in the given html input box without onclick function 'start_test'. but i want to start this inner function on button click which is not working. PLease help me to find the mistake.
function start_test() {
var hms = "01:30:00";
var a = hms.split(':'); // split it at the colons
// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
if( seconds > 0 ){
function secondPassed() {
var minutes = Math.round((seconds - 30)/60),
remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = " " +minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
//form1 is your form name
document.form_quiz.submit();
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
}
}
<div class="col-md-4" style="text-align: right;">
<button class="btn btn-primary" id="start_test" onclick="start_test();" >Start Test</button>
<input type="hidden" value="<?php echo date('M d Y');?>" id="c_month">
<h2><time id="countdown">01:30:00</time> </h2>
</div>
in setInterval(timePassed, 1000) this is 1s or MORE
=> 1000mms is just an indication, the time elapsed depend of the proccessor usage
PROOF:
const one_Sec = 1000
, one_Min = one_Sec * 60
, one_Hour = one_Min * 60
, biDigits = t => t>9?t:`0${t}`
, c_pseudo = document.getElementById('countdownP')
, c_real = document.getElementById('countdownR')
, btTest = document.getElementById('bt-test')
;
btTest.onclick=()=>
{
btTest.disabled = true
let [t_h,t_m,t_s] = '01:30:00'.split(':').map(v=>+v)
, timeEnd = new Date().getTime() + (t_h * one_Hour) + (t_m * one_Min) + (t_s * one_Sec)
, timerRef = setInterval(timePassed, 1000) // 1s or MORE !
;
function timePassed()
{
if (--t_s <0) { t_s = 59; --t_m}
if (t_m <0) { t_m = 59; --t_h }
c_pseudo.textContent = `${biDigits(t_h)}:${biDigits(t_m)}:${biDigits(t_s)}`
let tim = timeEnd - (new Date().getTime())
let tr_h = Math.floor(tim / one_Hour)
let tr_m = Math.floor((tim % one_Hour) / one_Min )
let tr_s = Math.floor((tim % one_Min ) / one_Sec )
c_real.textContent = `${biDigits(tr_h)}:${biDigits(tr_m)}:${biDigits(tr_s)}`
if ( !t_h && !t_m && !t_s)
{
btTest.disabled = false
clearInterval(timerRef)
}
}
}
<button id="bt-test" >Start Test</button>
<h2> pseudo count down <span id="countdownP">01:30:00</span> </h2>
<h2> real count down <span id="countdownR">01:30:00</span> </h2>
This statement is declaring a function countdownTimer, not executing it.
var countdownTimer = setInterval('secondPassed()', 1000);
Try replacing with:
setInterval(() => secondPassed(), 1000);
This should actually execute setInterval

How can I modify my function to be able to cancel the interval from anywhere in the controller

I am trying to create a countdown and I want to be able to cancel the interval not only when reach 0 but with clicking of a button as well.How can I modify my function to be able to cancel the interval from anywhere in the controller.
function countDown(total) {
total = total * 60;
var interval = $interval(function () {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1)
{
minutes = '0:';
}
else
{
minutes = minutes + ':';
}
if (seconds < 10)
{
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if(minutes === '0:' && seconds === '00')
{
$interval.cancel(interval);
}
}, 1000);
}
As suggested by other users, you should make interval global in the controller. Then on the other functions you want to cancel the interval you can call it safely.
Take a look at the below sample:
angular.module('app', [])
.controller('ctrl', function($interval) {
var self = this;
var interval;
self.wizard = {
startInterval: startInterval,
cancelInterval: cancelInterval
};
startInterval();
return self.wizard;
function startInterval() {
countDown(24);
}
function cancelInterval() {
$interval.cancel(interval);
}
function countDown(total) {
cancelInterval();
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.wizard.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<span ng-app="app" ng-controller="ctrl as ctrl">
<span ng-bind="ctrl.remainingTime"> </span>
<br/>
Cancel Interval
<br/>
Start Interval
</span>
I created an example using self instead of $scope like you are in your snippet above. As others mentioned moving the interval var to the global scope fixes this. I also added a stop and start function to test the issue you mentioned in the example above.
UPDATED - I added some code to the stop interval to reset the interval to undefined. I found an example of this usage on Angular's site so it might be worth a try to see if it fixes your other issue.
var app = angular.module('app', []);
app.controller('BaseController', function($interval) {
var self = this;
var interval;
function countDown(total) {
total = total * 60;
interval = $interval(function() {
var minutes = Math.floor(total / 60);
var seconds = total - minutes * 60;
if (minutes < 1) {
minutes = '0:';
} else {
minutes = minutes + ':';
}
if (seconds < 10) {
seconds = '0' + seconds;
}
self.remainingTime = "Remaining time: " + minutes + seconds;
total--;
if (minutes === '0:' && seconds === '00') {
$interval.cancel(interval);
}
}, 1000);
}
self.stopInterval = function(){
if (angular.isDefined(interval)) {
$interval.cancel(interval);
interval = undefined;
}
}
self.startInterval = function(){
countDown(10);
}
});
Then in the html I added a button to start and stop the interval like so:
<body ng-app="app">
<div ng-controller="BaseController as baseCtrl">
{{ baseCtrl.remainingTime }}
<div>
<button ng-click="baseCtrl.startInterval()">Start Countdown</button>
<button ng-click="baseCtrl.stopInterval()">Stop Countdown</button>
</div>
</div>
</body>
You can view the codepen example here

Javascript not displaying in browser

I'm following a tutorial about creating a timer in JavaScript but I can't get it to show up on my browser. I'm using Dreamweaver and it shows the timer just fine in a "live view" but in the browser window nothing is being displayed. What am I missing?
This is the main HTML page:
<html>
<head>
<script type="text/javascript" src="/Timer2.js" />
</head>
<body>
<div id='timer' />
<script type="text/javascript">
window.onload = CreateTimer("timer", 90);
</script>
</head>
</body>
</html>
This is the JavaScript timer function. timer2.js:
var Timer;
var TotalSeconds;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if (TotalSeconds <= 0) {
alert("Time's up!")
return;
}
TotalSeconds -= 1;
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function UpdateTimer() {
Timer.innerHTML = TotalSeconds;
}
function UpdateTimer() {
var Seconds = TotalSeconds;
var Days = Math.floor(Seconds / 86400);
Seconds -= Days * 86400;
var Hours = Math.floor(Seconds / 3600);
Seconds -= Hours * (3600);
var Minutes = Math.floor(Seconds / 60);
Seconds -= Minutes * (60);
var TimeStr = ((Days > 0) ? Days + " days " : "") + LeadingZero(Hours) + ":" + LeadingZero(Minutes) + ":" + LeadingZero(Seconds)
Timer.innerHTML = TimeStr ;
}
function LeadingZero(Time) {
return (Time < 10) ? "0" + Time : + Time;
}
You can't self-close a script tag. You MUST write <script ....></script>
Write <div id="timer"></div> and no <div id='timer' />
Delete your </head> at the bottom of the code, and if your script doesn't work again, try src="Timer2.js" without the "/"

Categories

Resources