Trying to display and update map markers using Leaflet JS - javascript

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.

Related

How do I make A and B run in parallel?

How do I make A and B run in parallel?
async function runAsync(funcName)
{
console.log(' Start=' + funcName.name);
funcName();
console.log(' End===' + funcName.name)
};
function A()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' A i= ' + i) ;
}
function B()
{
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 1000)
i++;
console.log(' B i= ' + i) ;
}
runAsync(A);
runAsync(B);
The console shows that A starts first and B starts after A:
Start=A
A i= 6515045
End===A
Start=B
B i= 6678877
End===B
Note:
I am trying to use async for Chrome/Firefox, and keep the JS code compatible with IE11.
This C# code generates the proxy function runAsync:
if (isEI())
Current.Response.Write(" function runAsync(funcName){ setImmediate(funcName); }; ");
else
Current.Response.Write(" async function runAsync(funcName){ funcName(); } ");
https://jsfiddle.net/NickU/n2huzfxj/28/
Update.
My goal was to parse information and prepare (indexing and adding triggers) for an immediate response after user input. While the user is viewing the information, the background function has 3-10 seconds to execute, and the background function should not block UI and mouse and keyboard responses. Here is the solution for all browsers, including IE11.
Created a new Plugin to simulate parallel execution of funcRun during idle times.
Example of an original code:
$("input[name$='xxx'],...").each( function(){runForThis(this)}, ticksToRun );
The updated code using the Plugin:
$(document).zParallel({
name: "Example",
selectorToRun: "input[name$='xxx'],...",
funcRun: runForThis
});
Plugin.
(function ($)
{
// Plugin zParallel
function zParallel(options)
{
var self = this;
self.defaults = {
selectorToRun: null,
funcRun: null,
afterEnd: null,
lengthToRun: 0,
iterScheduled: 0,
ticksToRun: 50,
showDebugInfo: true
};
self.opts = $.extend({}, self.defaults, options);
}
zParallel.prototype = {
init: function ()
{
var self = this;
var selector = $(self.opts.selectorToRun);
self.lengthToRun = selector.length;
if (self.lengthToRun > 0)
{
self.arrayOfThis = new Array;
selector.each(function ()
{
self.arrayOfThis.push(this);
});
self.arrayOfThis.reverse();
self.opts.iterScheduled = 0;
self.whenStarted = Date.now();
self.run();
return true;
}
else
{
this.out('zParallel: selector is empty');
return false;
}
},
run: function ()
{
var self = this;
var nextTicks = Date.now() + self.opts.ticksToRun;
var _debug = self.opts.showDebugInfo;
if (self.opts.iterScheduled === 0)
{
nextTicks -= (self.opts.ticksToRun + 1); // Goto to Scheduling run
}
var count = 0;
var comOut = "";
while ((self.lengthToRun = self.arrayOfThis.length) > 0)
{
var curTicks = Date.now();
if (_debug)
{
comOut = self.opts.name + " |" + (curTicks - self.whenStarted)/1000 + "s| ";
if (self.opts.iterScheduled === 0)
this.out("START " + comOut + " remaining #" + self.lengthToRun);
}
if (curTicks > nextTicks)
{
self.opts.iterScheduled++;
if ('requestIdleCallback' in window)
{
if (_debug)
this.out(comOut + "requestIdleCallback , remaining #" + self.lengthToRun + " executed: #" + count);
window.requestIdleCallback(function () { self.run() }, { timeout: 1000 });
} else
{
if (_debug)
this.out(comOut + "setTimeout, remaining #" + self.lengthToRun + " executed: #" + count);
setTimeout(function (self) { self.run()}, 10, self);
}
return true;
}
var nexThis = self.arrayOfThis.pop();
self.opts.funcRun(nexThis);
count++;
}
if (self.opts.afterEnd!== null)
self.opts.afterEnd();
if (_debug)
this.out("END " + comOut + " executed: #" + count);
return true;
},
out: function (str)
{
if (typeof console !== 'undefined')
console.log(str);
}
};
$.fn.zParallel = function (options)
{
var rev = new zParallel(options);
rev.init();
};
})(jQuery);
// Examples.
(function ($)
{
var tab1 = $('#tbl1');
for (i = 0; i < 1000; i++)
$("<tr>"+
"<td>#" + i + "</td>"+
"<td><input id='a_" + i + "' value='" + i + "' >"+
"</td><td><input id='b_" + i + "' value='" + i + "' ></td></tr>")
.appendTo(tab1);
$(document).zParallel({
name: "A",
selectorToRun: "input[id^='a_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('color', 'green').css('font-weight', 'bold');
else
$this.css('color', 'blue');
}
});
$(document).zParallel({
name: "B",
selectorToRun: "input[id^='b_']",
funcRun: function (nextThis)
{
var $this = $(nextThis);
var nowDateTime = Date.now();
var i = 0;
while( Date.now() < nowDateTime + 2)
i++;
$this.val( i );
if (i > 100)
$this.css('background', '#BBFFBB');
else
$this.css('background', '#FFBBBB');
}
});
})(jQuery);
https://jsfiddle.net/NickU/1xt8L7co/59/
The two example functions simply execute synchronously one after the other on the same "thread" (JS effectively has only one thread available to such scripts).
The use of async is irrelevant here because no truly asynchronous operation is occurring in function A - it is simply a busy while loop - so it completes in full before execution can move to anything else.
If function A had called an actual asynchronous operation (such as a HTTP request - not simply a synchronous operation wrapped in an async function), then function B may have a chance to start up (in which case B would complete entirely before the execution returned to A, because B is also only contains a synchronous, busy while loop).
Parallel processing can be achieved with WebWorkers which allowing running on background threads (actual separate threads).

How to implement codepen jquery script in wordpress?

I am trying to implement a fancy slider from codepen in wordpress. I have correctly added the script using the enqueue script method. I know I did it coorectly because it worked for a very small experiment I tried. Now the pen is: http://codepen.io/suez/pen/wMMgXp .
(function() {
var $$ = function(selector, context) {
var context = context || document;
var elements = context.querySelectorAll(selector);
return [].slice.call(elements);
};
function _fncSliderInit($slider, options) {
var prefix = ".fnc-";
var $slider = $slider;
var $slidesCont = $slider.querySelector(prefix + "slider__slides");
var $slides = $$(prefix + "slide", $slider);
var $controls = $$(prefix + "nav__control", $slider);
var $controlsBgs = $$(prefix + "nav__bg", $slider);
var $progressAS = $$(prefix + "nav__control-progress", $slider);
var numOfSlides = $slides.length;
var curSlide = 1;
var sliding = false;
var slidingAT = +parseFloat(getComputedStyle($slidesCont)["transition-duration"]) * 1000;
var slidingDelay = +parseFloat(getComputedStyle($slidesCont)["transition-delay"]) * 1000;
var autoSlidingActive = false;
var autoSlidingTO;
var autoSlidingDelay = 5000; // default autosliding delay value
var autoSlidingBlocked = false;
var $activeSlide;
var $activeControlsBg;
var $prevControl;
function setIDs() {
$slides.forEach(function($slide, index) {
$slide.classList.add("fnc-slide-" + (index + 1));
});
$controls.forEach(function($control, index) {
$control.setAttribute("data-slide", index + 1);
$control.classList.add("fnc-nav__control-" + (index + 1));
});
$controlsBgs.forEach(function($bg, index) {
$bg.classList.add("fnc-nav__bg-" + (index + 1));
});
};
setIDs();
function afterSlidingHandler() {
$slider.querySelector(".m--previous-slide").classList.remove("m--active-slide", "m--previous-slide");
$slider.querySelector(".m--previous-nav-bg").classList.remove("m--active-nav-bg", "m--previous-nav-bg");
$activeSlide.classList.remove("m--before-sliding");
$activeControlsBg.classList.remove("m--nav-bg-before");
$prevControl.classList.remove("m--prev-control");
$prevControl.classList.add("m--reset-progress");
var triggerLayout = $prevControl.offsetTop;
$prevControl.classList.remove("m--reset-progress");
sliding = false;
var layoutTrigger = $slider.offsetTop;
if (autoSlidingActive && !autoSlidingBlocked) {
setAutoslidingTO();
}
};
function performSliding(slideID) {
if (sliding) return;
sliding = true;
window.clearTimeout(autoSlidingTO);
curSlide = slideID;
$prevControl = $slider.querySelector(".m--active-control");
$prevControl.classList.remove("m--active-control");
$prevControl.classList.add("m--prev-control");
$slider.querySelector(prefix + "nav__control-" + slideID).classList.add("m--active-control");
$activeSlide = $slider.querySelector(prefix + "slide-" + slideID);
$activeControlsBg = $slider.querySelector(prefix + "nav__bg-" + slideID);
$slider.querySelector(".m--active-slide").classList.add("m--previous-slide");
$slider.querySelector(".m--active-nav-bg").classList.add("m--previous-nav-bg");
$activeSlide.classList.add("m--before-sliding");
$activeControlsBg.classList.add("m--nav-bg-before");
var layoutTrigger = $activeSlide.offsetTop;
$activeSlide.classList.add("m--active-slide");
$activeControlsBg.classList.add("m--active-nav-bg");
setTimeout(afterSlidingHandler, slidingAT + slidingDelay);
};
function controlClickHandler() {
if (sliding) return;
if (this.classList.contains("m--active-control")) return;
if (options.blockASafterClick) {
autoSlidingBlocked = true;
$slider.classList.add("m--autosliding-blocked");
}
var slideID = +this.getAttribute("data-slide");
performSliding(slideID);
};
$controls.forEach(function($control) {
$control.addEventListener("click", controlClickHandler);
});
function setAutoslidingTO() {
window.clearTimeout(autoSlidingTO);
var delay = +options.autoSlidingDelay || autoSlidingDelay;
curSlide++;
if (curSlide > numOfSlides) curSlide = 1;
autoSlidingTO = setTimeout(function() {
performSliding(curSlide);
}, delay);
};
if (options.autoSliding || +options.autoSlidingDelay > 0) {
if (options.autoSliding === false) return;
autoSlidingActive = true;
setAutoslidingTO();
$slider.classList.add("m--with-autosliding");
var triggerLayout = $slider.offsetTop;
var delay = +options.autoSlidingDelay || autoSlidingDelay;
delay += slidingDelay + slidingAT;
$progressAS.forEach(function($progress) {
$progress.style.transition = "transform " + (delay / 1000) + "s";
});
}
$slider.querySelector(".fnc-nav__control:first-child").classList.add("m--active-control");
};
var fncSlider = function(sliderSelector, options) {
var $sliders = $$(sliderSelector);
$sliders.forEach(function($slider) {
_fncSliderInit($slider, options);
});
};
window.fncSlider = fncSlider;
}());
/* not part of the slider scripts */
/* Slider initialization
options:
autoSliding - boolean
autoSlidingDelay - delay in ms. If audoSliding is on and no value provided, default value is 5000
blockASafterClick - boolean. If user clicked any sliding control, autosliding won't start again
*/
fncSlider(".example-slider", {autoSlidingDelay: 4000});
var $demoCont = document.querySelector(".demo-cont");
[].slice.call(document.querySelectorAll(".fnc-slide__action-btn")).forEach(function($btn) {
$btn.addEventListener("click", function() {
$demoCont.classList.toggle("credits-active");
});
});
document.querySelector(".demo-cont__credits-close").addEventListener("click", function() {
$demoCont.classList.remove("credits-active");
});
document.querySelector(".js-activate-global-blending").addEventListener("click", function() {
document.querySelector(".example-slider").classList.toggle("m--global-blending-active");
});
The javascript code can e found above and in the mentioned link.I know that in wordpress we have to use jQuery in place of $ but I still can't seem to figure out how to do it in this case. And one more thing, the css is in scass form but I have taken the compiled css form but I don't think that is causing any problem (rignt?) Everything I have tried till this point has failed. Any help will be appreciated
You can use $ instead of jQuery in WordPress so long as you wrap all your code inside the following:
(function($) {
// Your code goes here
})( jQuery );
If the code is in the header (before the document is ready) then instead use:
jQuery(document).ready(function( $ ) {
// Your code goes here
});
If your code is still having problems, then please include both the enqueue code in your theme and the error messages

Template.destroyed() not called

I'm displaying a timer showing the elapsed time since a collection item was created. However, when I navigate between Items (switch routes/url) the timer doesn't get destroyed and I end up having a bunch of leaked timers.
I could keep a reference to the timer and kill it in the router but I would prefer a cleaner way and handle it in the template. Any ideas?
<template name="itemDetails">
{{elapsedTime}}
</template>
Template.itemDetails.onRendered = function() {
var startTime = Template.currentData().startTime;
this.timeElapsed = new ReactiveVar;
this.taskTimer = Meteor.setInterval(function() {
var timeElapsedInMS = Date.now() - startTime;
var date = new Date(timeElapsedInMS);
var hours = (date.getUTCHours() < 10 ? '0' :'') + date.getUTCHours();
var minutes = (date.getUTCMinutes() < 10 ? '0' :'') + date.getUTCMinutes();
var seconds = (date.getUTCSeconds() < 10 ? '0' :'') + date.getUTCSeconds();
var timeElapsed = hours + ":" + minutes + ":" + seconds;
this.timeElapsed.set(timeElapsed);
console.log(timeElapsed);
}, 1000);
}
Template.itemDetails.helpers({
elapsedTime: function() {
return Template.timeElapsed.get();
}
});
Template.itemDetails.onDestroyed = function() {
Meteor.clearInterval(this.taskTimer);
}
I would do like this (template level) as well. Here is a quick example of how you could do a timer at template level:
<template name="test">
<p>Count: {{time}}</p>
</template>
Template.test.onCreated(function() {
var self = this;
self.time = new ReactiveVar(0);
self.taskTimer = Meteor.setInterval(function() {
self.time.set(self.time.get() + 1)
}, 1000);
});
Template.test.onDestroyed(function() {
Meteor.clearInterval(this.taskTimer);
});
Template.test.helpers({
time: function() {
var self = Template.instance();
return self.time.get();
}
});
I hope you can continue from here =)

JavaScript undefined function external JavaScript file

I have loaded an external JavaScript file, and placed functions within it, but when running the functions, it says "undefined function", but when I place the functions within the index file, it works perfectly.
To debug this, I wrote alert('entered'); when entering the document, and reading content when running and document is ready. Both are executed.
The error U get with this is:
Uncaught ReferenceError: countdown is not defined
Uncaught ReferenceError: keepalive is not defined
How can I fix this?
Source:
// JavaScript Document
alert('entered js.js');
$(document).ready(function() {
alert('reading content');
function countdown() {
var ele = document.getElementsByClassName('countdown');
for (var i = 0; i < ele.length; ++i) {
var v = Math.floor(ele[i].getAttribute('ctime')) - 1;
if (v < 0) {
v = 0;
}
ele[i].setAttribute('ctime', v);
if (v > 86399) {
var sl = v;
d = parseInt(sl / 86400);
sl = sl % 86400;
h = parseInt(sl / 3600);
sl = sl % 3600;
m = parseInt(sl / 60);
s = parseInt(sl % 60);
var str = d + 'd ' + h + 't ' + m + 'm ' + s + 's';
} else if (v > 3599) {
var h = Math.floor(v / 60 / 60);
var m = Math.floor((v - (h * 3600)) / 60);
var s = v - (m * 60) - (h * 3600);
var str = h + 't ' + m + 'm ' + s + 's';
} else if (v > 59) {
var m = Math.floor(v / 60);
var s = v - (m * 60);
var str = m + 'm ' + s + 's';
} else if (v > 0) {
var str = v + 's';
} else {
var str = ele[i].getAttribute('ctext') || '0s';
}
if (v == 0) {
var act = ele[i].getAttribute('caction');
if (act != '') {
setTimeout(function() {
url(act);
}, 1000);
}
}
ele[i].innerHTML = str;
}
setTimeout('countdown()', 1000);
}
$( ".specialpost tr" ).click(function(e) {
var form = $(this).parents('form').attr('id');
var submitformId = $(this).data("submitid");
console.log(form);
console.log(submitformId);
$("#submitvalue").val(submitformId);
$( "#" + form ).submit();
});
(function ($) {
$.fn.countTo = function (options) {
options = options || {};
return $(this).each(function () {
// set options for current element
var settings = $.extend({}, $.fn.countTo.defaults, {
from: $(this).data('from'),
to: $(this).data('to'),
speed: $(this).data('speed'),
refreshInterval: $(this).data('refresh-interval'),
decimals: $(this).data('decimals')
}, options);
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(settings.speed / settings.refreshInterval),
increment = (settings.to - settings.from) / loops;
// references & variables that will change with each update
var self = this,
$self = $(this),
loopCount = 0,
value = settings.from,
data = $self.data('countTo') || {};
$self.data('countTo', data);
// if an existing interval can be found, clear it first
if (data.interval) {
clearInterval(data.interval);
}
data.interval = setInterval(updateTimer, settings.refreshInterval);
// initialize the element with the starting value
render(value);
function updateTimer() {
value += increment;
loopCount++;
render(value);
if (typeof(settings.onUpdate) == 'function') {
settings.onUpdate.call(self, value);
}
if (loopCount >= loops) {
// remove the interval
$self.removeData('countTo');
clearInterval(data.interval);
value = settings.to;
if (typeof(settings.onComplete) == 'function') {
settings.onComplete.call(self, value);
}
}
}
function render(value) {
var formattedValue = settings.formatter.call(self, value, settings);
$self.text(formattedValue);
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 0, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
formatter: formatter, // handler for formatting the value before rendering
onUpdate: null, // callback method for every time the element is updated
onComplete: null // callback method for when the element finishes updating
};
function formatter(value, settings) {
return value.toFixed(settings.decimals);
}
}(jQuery));
function keepalive() {
$.ajax({
url : "http://www.smackface.net/check_user",
type : "POST",
dataType : 'json',
data : {
method : 'checkAlerts'
},
success : function(data, textStatus, XMLHttpRequest) {
var response = data;
if (!(response.login)) {
alert('You are now logging out');
} else {
if (response.messages > 0) {
$('#message_count').show().text(response.messages);
if ($('#message_count').text() != response.messages) {
$("#playsoundappend").html("<audio id=\"playsound\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"></audio>");
document.getElementById('playsound').play();
$('title').text(response.notifications + " messages");
}
}
else {
$('#message_count').hide();
}
if (response.notifications > 0) {
$('#notification_count').show().text(response.notifications);
if ($('#notification_count').text() != response.notifications) {
$("#playsoundappend").html("<audio id=\"playsound\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"><source src=\"http://soundbible.com/grab.php?id=1645&type=mp3\" type=\"audio/mpeg\"></audio>");
document.getElementById('playsound').play();
$('title').text(response.notifications + " notifications");
}
}
else {
$('#notification_count').hide();
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.responseText);
}
});
setTimeout('keepalive()', 10000);
}
$("#notificationLink").click(function()
{
$("#notificationContainer").fadeToggle(300);
$("#notification_count").fadeOut("slow");
$.ajax({
url : "http://www.smackface.net/check_user",
type : "POST",
dataType : 'json',
data : {
method : 'loadNotifications'
},
success : function(data, textStatus, XMLHttpRequest) {
var tpl = $("#notes").html();
var notification = Handlebars.compile(tpl);
$("#notificationsBody").html('');
$("#notificationsBody").append(notification(data));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(XMLHttpRequest.responseText);
}
});
return false;
});
$(document).click(function()
{
$("#notification_count").hide();
});
$("#notification_count").click(function()
{
return false;
});
keepalive();
countdown();
});
you can pass the function itself to setTimeout:
setTimeout(countdown, 1000);
setTimeout(keepAlive, 1000);
The way you wrote it, it will have to be 'eval'ed out of scope of $(document).ready(... . When you pass the function itself as the first argument, it is in scope.

Simple Time-Clock does not work with no errors

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/

Categories