I'm a beginner in Javascript and I'm having some trouble with this code I wrote. It's supposed to create a digital time-clock for my website.
If you're wondering why CPGS is in my functions/variable names it's because its a abbreviation for my website name :)
Also, I am getting NO console errors from FireBug and my JSLint confirms that my code is vaild.
Here's the code:
(function() {
function CpgsClock() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
}
CpgsClock.prototype.checker = function() {
if (this.cpgsHour === 0) {
this.cpgsPeriod = " AM";
this.cpgsHour = 12;
} else if (this.cpgsHour <= 11) {
this.cpgsPeriod = " AM";
} else if (this.cpgsHour === 12) {
this.cpgsPeriod = " PM";
} else if (this.cpgsHour <= 13) {
this.cpgsPeriod = " PM";
this.cpgsHour -= 12;
}
};
CpgsClock.prototype.setClock = function() {
document.getElementById('cpgstime').innerHTML = "" + this.cpgsHour + ":" + this.cpgsMin + this.cpgsPeriod + "";
};
var cpgsclock = new CpgsClock();
setInterval(function() {
cpgsclock.setClock();
cpgsclock.checker();
}, 1000);
})();
So setClock method works fine. But the checker won't do anything. As you can see it checks for the time and sets it to AM and PM accordingly. It doesn't do that for me.
Any help would be great!
You're not updating the clock in your setInterval...
CpgsClock.prototype.update = function() {
this.cpgsTime = new Date();
this.cpgsHour = this.cpgsTime.getHours();
this.cpgsMin = this.cpgsTime.getMinutes();
this.cpgsDay = this.cpgsTime.getDay();
this.cpgsPeriod = "";
};
And in your setInterval :
setInterval(function() {
cpgsclock.update();
cpgsclock.checker();
cpgsclock.setClock();
}, 1000);
jsFiddle : http://jsfiddle.net/qmSua/1/
Related
I have been trying to make a debounce system that is ID based using unix timestamp i want it to print passed if it hasn't been called at all in the past second if it has print failed(with that specific id)
I can't figure out what exactly is going wrong i've tried everything I can imagine
I have recreated the problem in a testfile i've pasted the code below
const Cooldowns = {}
function Test(ID) {
const CurrentDate = Date.now();
let IsReal = false;
if (Cooldowns[ID]) {
IsReal = true;
};
console.log(Cooldowns[ID])
console.log(IsReal)
if (Cooldowns[ID] < CurrentDate || !(IsReal)) {
Cooldowns[ID] = CurrentDate + 1;
console.log(ID + " Time " + CurrentDate + " Passed");
} else {
console.log(ID + " Time " + CurrentDate + " Failed");
};
}
Test(12);
Test(19);
setTimeout(() => {
console.log("----------------------------------------------------");
Test(12);
Test(19);
Test(2);
setTimeout(() => {
console.log("-----------------------------------------------------");
Test(12);
Test(19);
Test(2);
}, 500);
}, 1050);
I'm a backend developer, who's trying hard to make a timer by comparing two different date formats. This part of the script is working great, but whenever I try to make recursive call, nothing is binding.
I almost tried everything, from passing it into a function, using the $interval, the setInterval, and on and on. The main reason is I cannot get the value of its loop, and binding into my DOM.
Here is some of my code. Here I set all variables for the countDown() function.
$scope.timer.list = {};
$scope.timer.date = new Date();
$scope.timer.list.D = '00';
$scope.timer.list.M = '00';
$scope.timer.list.Y = '00';
$scope.timer.list.h = '00';
$scope.timer.list.m = '00';
$scope.timer.list.s = '00';
$scope.begin = {};
$scope.begin.date = {};
$scope.begin.timer = {};
$scope.counter = {
show : false,
text : '00:00'
};
setInterval(function() {
$scope.obj = {
show : $scope.countDown($scope.privateshowcase.begin_at).show,
text : $scope.countDown($scope.privateshowcase.begin_at).text
}
$scope.counter = $scope.obj;
}, 1000);
Then, here is the function:
$scope.countDown = function(begin) {
$scope.timer.date = new Date();
$scope.timer.list.D = $filter('date')($scope.timer.date, 'dd');
$scope.timer.list.M = $filter('date')($scope.timer.date, 'MM');
$scope.timer.list.Y = $filter('date')($scope.timer.date, 'yyyy');
$scope.timer.list.h = $filter('date')($scope.timer.date, 'HH');
$scope.timer.list.m = $filter('date')($scope.timer.date, 'mm');
$scope.timer.list.s = $filter('date')($scope.timer.date, 'ss');
$scope.begin.full = begin.split(" ");
$scope.begin.date = $scope.begin.full[0].split("-");
$scope.begin.timer = $scope.begin.full[1].split(":");
$scope.begin.D = $scope.begin.date[2];
$scope.begin.M = $scope.begin.date[1];
$scope.begin.Y = $scope.begin.date[0];
$scope.begin.h = $scope.begin.timer[0];
$scope.begin.m = $scope.begin.timer[1];
$scope.begin.s = $scope.begin.timer[2];
if($scope.timer.list.Y == $scope.begin.Y) {
if($scope.timer.list.M == $scope.begin.M) {
if($scope.timer.list.D == $scope.begin.D) {
$scope.counter.diff_h = $scope.timer.list.h - $scope.begin.h;
if($scope.counter.diff_h == 0 || $scope.counter.diff_h == -1) {
if($scope.counter.diff_h == 0) {
if($scope.timer.list.m > $scope.begin.m) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if ($scope.timer.list.m <= $scope.begin.m) {
$scope.counter.show = true;
$scope.counter.diff_m = $scope.begin.m - $scope.timer.list.m;
if($scope.counter.diff_m <= 30) {
$scope.counter.diff_s = 60 - $scope.timer.list.s;
if($scope.counter.diff_s == 60) {
$scope.counter.s = "00";
$scope.counter.diff_m_f = $scope.counter.diff_m + 1;
} else if($scope.counter.diff_s >= 1 && $scope.counter.diff_s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_s;
$scope.counter.diff_m_f = $scope.counter.diff_m;
}
if($scope.counter.diff_m_f >= 1 && $scope.counter.diff_m_f <= 9) {
$scope.counter.m = "0" + $scope.counter.diff_m_f;
} else {
$scope.counter.m = $scope.counter.diff_m_f;
}
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else if ($scope.counter.diff_h == -1) {
$scope.counter.diff_timer = $scope.timer.m - 60;
$scope.counter.diff_m = $scope.begin.m - $scope.counter.diff_timer;
if($scope.counter.diff_m > 30) {
$scope.counter.show = false;
$scope.counter.text = false;
} else if($scope.counter.diff_m <= 30) {
$scope.counter.show = true;
$scope.counter.diff_timer_s = $scope.timer.s - 60;
if($scope.counter.diff_timer_s == 60) {
$scope.counter.s = "00";
$scope.counter.m = $scope.counter.diff_m + 1;
} else if($scope.counter.s >= 1 && $scope.counter.s <= 9) {
$scope.counter.s = "0" + $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
} else {
$scope.counter.s = $scope.counter.diff_timer_s;
$scope.counter.m = $scope.counter.diff_m;
}
$scope.counter.text = $scope.counter.m + ":" +$scope.counter.s;
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
} else {
$scope.counter.show = false;
$scope.counter.text = false;
}
return $scope.counter = {
show : $scope.counter.show,
text : $scope.counter.text
};
}
'begin' is : 'YYYY/MM/DAY HH:MM:SS'
Maybe my way of thinking is not the good one, but at list I have a very functional timer, which replace every 1 to 9 into 01 to 09, convert the 60 into 00, can compare 2 different hours.
I think you are over complicating things a little bit. I came up with a simple countDown component made in angularjs 1.6.0 (it can be done with directives for angularjs older versions as well) that compares an input Date with the now Date.
You can play around with the input and change dates to see changes happen on the component, as long as you don't break the date format.
Note on dates: simple way to compare dates:
var date0 = new Date("2017-09-12T14:45:00.640Z");
var date1 = new Date("2017-09-13T14:45:00.640Z");
var dateDiff = new Date(date1.getTime() - date0.getTime());
// "1970-01-02T00:00:00.000Z"
Although dateDiff looks weird, it's basically one day from the zero date 1970-01-01T00:00:00.000Z.
Given that, you just let angularjs do the magic (or maybe trick).
{{ dateDiff | date:"d \'days\' hh:mm:ss" }}
Besides, if you don't want to work with dates in the natural form of javascript, you can use angularjs-moment which provide you date and time utility from momentjs regardless of javascript dates pitfalls.
Here is the working code:
angular
.module('app', [])
.run(function($rootScope) {
$rootScope.countDownToDate = new Date().addDays(2);
})
.component('countDown', {
template: '{{ $ctrl.timer | date:"d \'days\' hh:mm:ss" }}',
bindings: {
to: '<'
},
controller: function CountDownCtrl($interval) {
var $this = this;
this.$onInit = function() {
$interval($this.setTime, 1000);
};
$this.setTime = function() {
$this.timer = new Date(new Date($this.to).getTime() - new Date().getTime());
}
}
});
// bootstrap the app
angular.element(function() {
angular.bootstrap(document, ['app']);
});
// extension to add days on date
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<div>
<center>
<h1>
<count-down to="countDownToDate" />
</h1>
<label for="countDownToDate">To Date</label>
<input type="datetime" name="countDownToDate" ng-model="countDownToDate">
</center>
</div>
I am trying to create a countdown with JQuery. I have different times in an array. When the first time ist finished, the countdown should count to the next time in the array.
I try to do this with the JQuery countdown plugin:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
while (i < time.length) {
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
i++;
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
This does not work... But how can i do this?
You should never use a busy wait especially not in the browser.
Try something like this:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
var $counter = $("#countdown");
function countdown() {
var goal = date + " " + time[i];
$counter.countdown(goal, function(event) {
if (event.elapsed) {
i++;
if (i < time.length) {
countdown();
}
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
You can't use while or for loop in this case, because the operation you want to perform is not synchronous.
You could do for example something like this with the helper (anonynous) function:
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
var i = 0;
(function countdown(i) {
if (i === time.length) return;
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
countdown(i++);
} else {
$(this).text(event.strftime('%H:%M:%S'));
}
});
})(0)
You need to restart the countdown when the previous one finishes, at the minute you're starting them all at the same time.
var date = "2017/04/25";
var time = ["13:30:49", "14:30:49", "16:30:49", "17:30:49"];
function startCountdown(i) {
if(i >= i.length) {
return;
}
var goal = date + " " + time[i];
$("#countdown")
.countdown(goal, function(event) {
if (event.elapsed) {
startCountdown(i++);
} else {
$(this).text(
event.strftime('%H:%M:%S')
);
}
});
}
startCountdown(0);
I'm trying to display countdown timers until each of my markers disappear on my map. The markers disappear when their respective timers run out, but the timers themselves are not displaying below the markers themselves as they should. I checked the Developer Console and noticed there are a couple errors:
Uncaught TypeError: Cannot read property 'innerHTML' of null
Uncaught ReferenceError: component is not defined
This error count keeps increasing until it stops at a high number. I'm guessing this is when the particular timer runs out because after that number stops climbing the same error is logged again and the number starts from 1 and continues to climb.
L.HtmlIcon = L.Icon.extend({options: {},
initialize: function(options) {
L.Util.setOptions(this, options);
},
createIcon: function() {
//console.log("Adding pokemon");
var div = document.createElement('div');
div.innerHTML =
'<div class="displaypokemon" data-pokeid="' + this.options.pokemonid + '">' +
'<div class="pokeimg">' +
'<img src="data:image/png;base64,' + pokemonPNG[this.options.pokemonid] + '" />' +
'</div>' +
'<div class="remainingtext" data-expire="' + this.options.expire + '"></div>' +
'</div>';
return div;
},
createShadow: function() {
return null;
}
});
var map;
function deleteDespawnedPokemon() {
var j;
for (j in shownMarker) {
var active = shownMarker[j].active;
var expire = shownMarker[j].expire;
var now = Date.now();
if (active == true && expire <= now) {
map.removeLayer(shownMarker[j].marker);
shownMarker[j].active = false;
}
}
}
function createPokeIcon(pokemonid, timestamp) {
return new L.HtmlIcon({
pokemonid: pokemonid,
expire: timestamp,
});
}
function addPokemonToMap(spawn) {
var j;
var toAdd = true;
if (spawn.expiration_timestamp_ms <= 0){
spawn.expiration_timestamp_ms = Date.now() + 930000;
}
for (j in shownMarker) {
if (shownMarker[j].id == spawn.encounter_id) {
toAdd = false;
break
}
}
if (toAdd) {
var cp = new L.LatLng(spawn.latitude, spawn.longitude);
var pokeid = PokemonIdList[spawn.pokemon_id];
var pokeMarker = new L.marker(cp, {
icon: createPokeIcon(pokeid, spawn.expiration_timestamp_ms)
});
shownMarker.push({
marker: pokeMarker,
expire: spawn.expiration_timestamp_ms,
id: spawn.encounter_id,
active: true
});
map.addLayer(pokeMarker);
pokeMarker.setLatLng(cp);
}
}
//TODO:<--Timer Functions-->//
function calculateRemainingTime(element) {
var $element = $(element);
var ts = ($element.data("expire") / 1000 | 0) - (Date.now() / 1000 | 0);
var minutes = component(ts, 60) % 60,
seconds = component(ts, 1) % 60;
if (seconds < 10)
seconds = '0' + seconds;
$element.html(minutes + ":" + seconds);
}
function updateTime() {
deleteDespawnedPokemon();
$(".remainingtext, .remainingtext-tooltip").each(function() {
calculateRemainingTime(this);
});
}
setInterval(updateTime, 1000);
//<--End of timer functions-->//
Here is my JSFiddle for a full view of the situation.
Any idea what I'm doing wrong?
SolutionThanks to user T Kambi for pointing out the issue!
I forgot to include the component() function.
function component(x, v) {
return Math.floor(x / v);
}
After including this all works as intended.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have a html button that is hooked up to a JQuery function at the top of my page, but the click does not seem to be firing? Is there something I'm missing?
$(function(){
$('#ctl00_content_hidePast').click(function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
And the button:
<button id="ctl00_content_hidePast"><i class='fa fa-eye-slash'></i> Hide/Show Past Bookings</button>
try
$(function(){
$(document).on('click','#ctl00_content_hidePast', function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
In this case you bind the event to the document. This is usually used when you have dynamic dom elements. You don't need to bind the click event to the document. Actually it's recommended to attach it to non dynamic parent. For example the div that will contain the buttons. In that case the code would be:
$(document).on('click','div that contains the buttons selector', function() ..
It just makes things lighter. But since I don't have the dom structure I gave you an answer that will work in any case.
If you are using a dynamic button you have to use the following:
$(function(){
$('#ctl00_content_hidePast').on("click", function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});
or (Deprecated)
$(function(){
$('#ctl00_content_hidePast').live("click", function() {
var dt = new Date($.now() - 30 * 60000);
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
$("td.bgtime").each(function() {
var bookingTime = ($(this).text().split(':'));
var d = new Date();
d.setHours(+bookingTime[0]);
d.setMinutes(bookingTime[1]);
var state = $("#ctl00_content_hdnPastBookingToggle").val();
if ($(d) > time) {
var timeRow = $(this).parent();
$(timeRow).toggle("slow",
function() {
if (state.val === "0") {
state.val = "1";}
else if (state.val === "1") {
state.val = "0";
};
});
};
});
});
});