Increment variable Javascript since a date - javascript

Hi I want to use 3 different counters that show me 3 different increasing numbers starting from a certain date. I've tryed this:
<script>
var START_DATE_1 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_1 = 5; // in seconds
var INCREMENT_1 = 1; // increase per tick
var START_VALUE_1 = 0; // initial value when it's the start date
var count_1 = 0;
window.onload = function()
{
var msInterval_1 = INTERVAL_1 * 1000;
var now_1 = new Date();
count_1 = parseInt((now_1 - START_DATE_1)/msInterval_1) * INCREMENT_1 + START_VALUE_1;
document.getElementById('counter_1').innerHTML = count_1;
setInterval("count_1 += INCREMENT_1; document.getElementById('counter_1').innerHTML = count_1;", msInterval_1);
}
</script>
<script>
var START_DATE_2 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_2 = 5; // in seconds
var INCREMENT_2 = 1; // increase per tick
var START_VALUE_2 = 0; // initial value when it's the start date
var count_2 = 0;
window.onload = function()
{
var msInterval_2 = INTERVAL_2 * 1000;
var now_2 = new Date();
count_2 = parseInt((now_2 - START_DATE_2)/msInterval_2) * INCREMENT_2 + START_VALUE_2;
document.getElementById('counter_2').innerHTML = count_2;
setInterval("count_2 += INCREMENT_2; document.getElementById('counter_2').innerHTML = count_2;", msInterval_2);
}
</script>
<script>
var START_DATE_3 = new Date("July 18, 2016 10:30:00"); // put in the starting date here
var INTERVAL_3 = 5; // in seconds
var INCREMENT_3 = 1; // increase per tick
var START_VALUE_3 = 0; // initial value when it's the start date
var count_3 = 0;
window.onload = function()
{
var msInterval_3 = INTERVAL_3 * 1000;
var now_3 = new Date();
count_2 = parseInt((now_3 - START_DATE_3)/msInterval_3) * INCREMENT_3 + START_VALUE_3;
document.getElementById('counter_3').innerHTML = count_2;
setInterval("count_3 += INCREMENT_3; document.getElementById('counter_3').innerHTML = count_3;", msInterval_3);
}
</script>
<div id="counter_1"></div>
<div id="counter_2"></div>
<div id="counter_3"></div>
This doesn't work as expected and only the 3td div is populated but now working as expected too (as soon as I load the page it show me a number then after few seconds restart from 1).
What's wrong? How should I do it without using JQuery also?
Thanks in advance.

I don't do a code analysis - this would be something for SE-CodeReview (highly recommended to post there too once you got it working), but your error is, that you are assigning something to a function more than once - hence, only the last assignment is actually called onload.
So -- you are assigning window.onload = function() in your first <script> tag, then you are overriding it in your second; and you're overriding the second assignment again in your third <script> tag.
You can't do that if you want to assign all 3 functions to a single (onload) event.
If you want to add multiple listeners for a single event, use
document.addEventListener("DOMContentLoaded", function() {});
Now inside that function, you can add all your code that you want to have executed onload of your page; in addition to the code you wanted to have executed onload in another function!
Here's a simple demonstration using the same techniques as described above, but with click listeners. Notice the first function will never be called.
document.getElementById("a").onclick = function() {
alert("I will never alert, because of the next function");
}
document.getElementById("a").onclick = function() {
alert("I will alert, because I'm not overriden");
}
document.getElementById("a").addEventListener('click', function() {
alert("I will alert too");
});
document.getElementById("a").addEventListener('click', function() {
alert("And a third alert. Disturbing");
});
<div id="a">Click me!</div>

Related

How to stop Javascript counter after initial result is returned

I need to stop a counter after returning its initial result so that the result can then be innerHTL inserted as a static number off which subsequent, separate scripts rely.
The counter works great for continual counting, but I can't stop the darned thing for the life of me.
I've tried clearInterval, stopPropagation, modifying variables, but I'm honestly just too much of a disaster to know where to make those (or other) changes to stop and hold the initial returned value.
var counterData = {'startCounter':'1','startingDate':'02\/01\/2019','incrementPerSecond':'2','counterInterval':'3'};
var canYouBelieveThisGuy = function () {
'use strict';
if ($("#stat_counter").length > 0) {
var currentstat = parseFloat(counterData['startCounter'].replace(/[^\d.-]/g,''));
var intervalSeconds = counterData['counterInterval'] * 1000; //1000;
var increaseUnit = counterData['incrementPerSecond'];
var initialDate = new Date(counterData["startingDate"]);
setInterval(function () {
var currentDate = new Date();
var timeDiffSeconds = (currentDate - initialDate)/1000;
var increment = timeDiffSeconds * increaseUnit;
var currentstat2 = parseInt(currentstat + increment) * 100;
currentstat2 = (currentstat2 / 100).toFixed(0)
var num = (currentstat2);
$("#stat_counter").text(num);
}, intervalSeconds);
};
}
(jQuery, this);
The returned value should be the number produced after the initial run, and should stop running entirely thereafter.
Thanks for the help and for being gentle!

reloading div doesn't update time if it's called from another function

I have a time function
function hm()
{
var d = new Date();
var h = ('0'+d.getHours()).substr(-2);
var m = ('0'+d.getMinutes()).substr(-2);
var str0 = h + ':' + m;
return {date: str0, hour: h, minute: m};
}
var hm = hm();
var date = hm.date;
var hour = hm.hour;
var minute = hm.minute;
and I have a div
<div id="mytime">Time</div>
I call time function from this which updates the div
function refreshDiv() {
document.getElementById('mytimer').innerHTML = 'Time:.....' + hm.date;
}
$(document).ready(function () {
setInterval(refreshDiv, 5000);
});
It won't update the time like 12:03 12:04 but if I place function hm() and variables var hm = hm(); var date = hm.date; into function refreshDiv() block it works.
How can I make it work?
EDIT:
This is a nwjs project.
If I add hm = hm(); inside refreshDiv() I get:
"Uncaught TypeError: object is not a function", source: file:///home/.../index.html (182)
182 is line number of included hm = hm();
You don't need to store individual values:
var hm = hm();
var date = hm.date;
var hour = hm.hour;
var minute = hm.minute;
You have a function hm(): call it, and immediately get the value of a returned object:
document.getElementById('mytimer').innerHTML = 'Time: ' + hm().date;
Why? Let's use Chrome DevTools to clarify this.
So, you defined a function hm().
When you call it, you get the returned object: {a: 0000000000000, b: "test"}
You can access the fields of this object with .
var object = hm(); // Assign the returned value of hm() to object
alert(object.a); // Alerts value of the field a of object
If you don't want to allocate new variables, use hm().a. You will conserve memory and time.

Detect change in timer variable using jQuery

I have certain timers which are updating every second. I want to execute some function on change of timer variable. If anyone can help me out. I have provided the code below.
for(var i=0; i<listingTime.length; i++){
if (listingTime[i].time >= 0) {
var second = listingTime[i].time / 1000;
var currentHour = parseInt(second / 3600);
}
}
Here, I want to detect change of currentHour variable.
You can set a previous value variable prior to the loop, and whenever updating the currentHour, just match it with previousValue variable. If they are same, they are not changes, if they are not same, it is changed and you can execute the callback.
One more other way is to use the object prototypes to changes the value of currentHour. Following code shows that:
Above code can be modified to following to add a changeListner
var HourListner = {
currentHour: null,
update: function(newValue, callback){
if(this.currentHour !== newValue){
this.currentHour = newValue;
callback(newValue);
}
}
}
timer = Object.create(HourListner);
var changeListner = function(value){
//value is the new value of currentHour
console.log(value)
}
for(var i=0; i<listingTime.length; i++){
if (listingTime[i].time >= 0) {
var second = listingTime[i].time / 1000;
var currentHour = parseInt(second / 3600);
timer.update(currentHour, changeListner)
}
}
And the trick can be tested independently in following code:
var HourListner = {
currentHour: null,
update: function(newValue, callback) {
if (this.currentHour !== newValue) {
this.currentHour = newValue;
callback(newValue);
}
}
}
timer = Object.create(HourListner);
var changeListner = function(value) {
//value is the new value of currentHour
console.log(value)
$('body').append('<p>'+value+'</p>')
}
var interval = setInterval(function(){
var t = new Date();
timer.update(t.getMinutes(), changeListner)
}, 200)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This will execute the changeListner if there is a change from previous value.

2 javascripts not working with each other

I have 2 javascripts who aren't working together. They both work separately, but when put together only one works. This is how I called them
window.onload = initImages;
window.onload = countdown(year,month,day,hour,minute);
If I put "window.onload = initImages;" after "countdown", then only images work, if it stays like this when countdown is after images, then only countdown works.
// JavaScript Document
function initImages() {
for (var x = 0; x < document.images.length; x++)
{
document.images[x].onclick = povecana;
}
}
function povecana() {
dir = "images/" + this.id + ".jpg";
if (undefined != window.proz)
{
proz.style.opacity = 0.6;
}
proz = document.getElementById(this.id);
proz.style.opacity = 1;
slika = document.getElementById("odabranaSlika");
slika.style.display= "block";
slika.innerHTML='<img src='+ dir +' " width="100%" height="450px" />';
jabuke = document.getElementById("default");
jabuke.style.display= "none";
tekst = document.getElementById("tekstOdabrane");
tekst.style.display = "block";
if (this.id=="slika1")
tekst.innerHTML="Idared je američka sorta nastala 1935.";
else (this.id=="slika2")
tekst.innerHTML="Fuji je zasigurno jedna od atraktivnijih";
}
/*
Count down until any date script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free scripts here!
Modified by Robert M. Kuhnhenn, D.O.
on 5/30/2006 to count down to a specific date AND time,
on 10/20/2007 to a new format, and 1/10/2010 to include
time zone offset.
*/
/* Change the items noted in light blue below to create your countdown target date and announcement once the target date and time are reached. */
var current="Winter is here!";//-->enter what you want the script to display when the target date and time are reached, limit to 20 characters
var year=2013; //-->Enter the count down target date YEAR
var month=12; //-->Enter the count down target date MONTH
var day=21; //-->Enter the count down target date DAY
var hour=18; //-->Enter the count down target date HOUR (24 hour clock)
var minute=38; //-->Enter the count down target date MINUTE
var tz=+1; //-->Offset for your timezone in hours from UTC (see http://wwp.greenwichmeantime.com/index.htm to find the timezone offset for your location)
//--> DO NOT CHANGE THE CODE BELOW! <--
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
function countdown(yr,m,d,hr,min){
theyear=yr;themonth=m;theday=d;thehour=hr;theminute=min;
var today=new Date();
var todayy=today.getYear();
if (todayy < 1000) {todayy+=1900;}
var todaym=today.getMonth();
var todayd=today.getDate();
var todayh=today.getHours();
var todaymin=today.getMinutes();
var todaysec=today.getSeconds();
var todaystring1=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec;
var todaystring=Date.parse(todaystring1)+(tz*1000*60*60);
var futurestring1=(montharray[m-1]+" "+d+", "+yr+" "+hr+":"+min);
var futurestring=Date.parse(futurestring1)-(today.getTimezoneOffset()*(1000*60));
var dd=futurestring-todaystring;
var dday=Math.floor(dd/(60*60*1000*24)*1);
var dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
var dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
var dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);
if(dday<=0&&dhour<=0&&dmin<=0&&dsec<=0){
document.getElementById('count2').innerHTML=current;
document.getElementById('count2').style.display="inline";
document.getElementById('count2').style.width="390px";
document.getElementById('dday').style.display="none";
document.getElementById('dhour').style.display="none";
document.getElementById('dmin').style.display="none";
document.getElementById('dsec').style.display="none";
document.getElementById('days').style.display="none";
document.getElementById('hours').style.display="none";
document.getElementById('minutes').style.display="none";
document.getElementById('seconds').style.display="none";
document.getElementById('spacer1').style.display="none";
document.getElementById('spacer2').style.display="none";
return;
}
else {
document.getElementById('count2').style.display="none";
document.getElementById('dday').innerHTML=dday;
document.getElementById('dhour').innerHTML=dhour;
document.getElementById('dmin').innerHTML=dmin;
document.getElementById('dsec').innerHTML=dsec;
setTimeout("countdown(theyear,themonth,theday,thehour,theminute)",1000);
}
}
window.onload = function() {
initImages();
countdown(year,month,day,hour,minute);
}
They are being overwritten. You can't assign two values to one variable!
For example,
x = 5;
x = 10;
Of course, x will be 10. Well, it is the same for you: window.onload is like x and the numbers are like your functions.
window.onload = func1;
window.onload = func2;
in this case always func 2 will be called as you have changed the onload handler from func1 to func2 after the 2nd statement;
try
window.onload = function(){
func1();
func2();
}

setInterval delays

I'm trying to execute a rotating banner (Calling it through an array). I set an interval but the image only shows after 10 seconds (10000) and only then begins the rotation. I removed the cluttered HTML of the array, but here's the rest of it:
var current = 0;
var banners = new Array();
banners[0]=;
banners[1]=;
banners[2]=;
banners[3]=;
var myTimeout = setInterval("rotater()",10000);
function rotater() {
document.getElementById("placeholderlayer").innerHTML=banners[current];
if(current==banners.length-1){
current = 1;
}else{
current += 1;
}
}
window.onload = rotater();
window.onload = rotater;
is the correct syntax. You don't want to call the function. However, the bulletproof solution is rather this:
onload = function() {
rotater();
window.myTimeout = setInterval(rotater, 10000); // Never pass a string to `setInterval`.
};
ProTip™: Don't use new Array(), use an array literal. For example, this:
var arr = new Array();
arr[0] = 'Hello';
arr[1] = 'world!';
Should be written as:
var arr = ['Hello', 'world!'];
Just a comment:
Instead of:
if(current==banners.length-1) {
current = 1;
} else {
current += 1;
}
you can do:
current = ++current % banners.length;

Categories