I just created a simple JavaScript counter. The first version adds a constant every second to an initial value; the second version adds 1 to the initial value in a proportionately reduced amount of time. I'm not rounding any numbers. But if you let the counter run long enough, the resulting values start diverging considerably. Any idea why that is?
window.onload = function() {
var Today = new Date();
var Jan = new Date("January 1 2020 00:00");
var dif = (Today.getTime() - Jan.getTime()) / 1000;
const Clklid = 3.55988;
var new1 = Clklid * dif;
var new2 = Clklid * dif;
var text = document.getElementById("text")
var text2 = document.getElementById("text2")
setInterval(function() {
new1 += Clklid;
// new1 = Math.trunc(new1);
text.innerHTML = new1 + " g emisí CO2";
}, 1000);
setInterval(function() {
new2 += 1;
// new2 = Math.trunc(new2);
text2.innerHTML = new2 + " g emisí CO2";
}, 1000 / Clklid);
}
<div id="text"></div>
<div id="text2"></div>
https://jsfiddle.net/6t4b1sqk/
setInterval is not perfect and actually takes up to 5 milliseconds longer for each iteration. Intervals that update more often will be behind one that update less.
If you want the 2 timers to always show similar values, only use one counter (replace new1 and new2 with new)
Alternatively, have both counters update in one function and not in the other:
setInterval(function() {
new1 += Clklid;
new2 += 1;
// new1 = Math.trunc(new1);
// new2 = Math.trunc(new2);
text.innerHTML = new1 + " g emisí CO2";
}, 1000);
setInterval(function() {
// new2 = Math.trunc(new2);
text2.innerHTML = new2 + " g emisí CO2";
}, 1000 / Clklid);
Related
I create time using toLocaleString() and then I use this code to change the color every sec but it work only last color not for all.
var time=document.getElementById("time");
setInterval(function() {
var da=new Date();
var ti=da.toLocaleTimeString();
// console.log("yes");
time.innerHTML=ti;
}, 1000);
setInterval(function() {
var arr=["red","blue","green"];
var i=Math.floor(Math.random() * 2) + 1;
// console.log(i);
time.style.color=time.classList.add(arr[i]);
console.log(i);
}, 1000);
You can try this trick to achieve the requirement you have.
To get the colors in sequence, try this :
var time=document.getElementById("time");
var arr=["red","blue","green"];
let index = 0;
setInterval(function() {
var da = new Date();
var ti = da.toLocaleTimeString();
time.innerHTML = ti;
time.style.color = arr[index];
if (index < arr.length) { index++; } else { index = 0 }
}, 1000);
<div id="time"></div>
To get the random color from an array, try this :
var time=document.getElementById("time");
var arr=["red","blue","green"];
setInterval(function() {
var da = new Date();
var ti = da.toLocaleTimeString();
time.innerHTML = ti;
const index = Math.floor(Math.random() * arr.length);
time.style.color = arr[index];
}, 1000);
<div id="time"></div>
Please i have a JavaScript countdown timer code that i got from stackoverflow that is a solution to my countdown timer project. this existing code counts down time from 30minutes down to 1 and start over again. and it gives the same count result to every user at the same time. But my challenge with the code is that i was not able to modify it in other to be able to regulate the count duration, because i want it to countdown from 2minutes to 0 and start over again continually,but not exceeding 2minutes. Please i need someone that will copy this code and run it a see if you can regulate the duration and help me with the solution. thanks in anticipation.
The code is as follows:
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
The code you presented deserves a few remarks:
Variable names should be descriptive, not one-letter a, b, c...
Variables should be defined explicitly, not implicitly global, like now happens for y and q
When m is 30, then y does not get a value... this cannot be right.
If that last point would be corrected, then the logic for setting z would pose a new problem.
Styling should be done as much as possible via CSS classes, not via style attribute settings.
Here is how you could do it. You can set the first two constants to your liking:
// Maximum number of seconds for the timer (e.g. 120 = 2 minutes)
const MAX_SECS = 120;
// Number of seconds below which text gets highlighted
const WARN_SECS = 15;
// DOM
const spanMinutes = document.getElementById("min");
const spanSeconds = document.getElementById("sec");
const spanWarning = document.getElementById("break");
// For formatting numbers with 2 digits
const twoDigits = i => i.toString().padStart(2, 0);
setInterval(() => {
let seconds = MAX_SECS - Math.floor(Date.now() / 1000) % MAX_SECS;
spanMinutes.textContent = twoDigits(Math.floor(seconds / 60))
spanSeconds.textContent = twoDigits(seconds % 60);
spanWarning.classList.toggle("warn", seconds < WARN_SECS);
}, 250);
#timer {
text-align: center;
font-size: 24px;
}
.warn {
color: red;
}
<div id="timer"><span id="min">00</span>:<span id="sec">00</span>
till station <span id="break">breaks down</break>
</div>
Setting up a sales page and I can't get the product inventory countdown timer to work on other products on the page.
I got it working for the first product but it doesn't wanna work on the second product. Same Page.
// Random Countdown Timer Script, by http://ctrtard.com
var timer;
function startCount() {
timer = setInterval(count, 200); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
var rand_no = Math.ceil(9 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "Sold Out"; // This message is displayed when the counter reaches zero.
}
}
<body onLoad="startCount();">
<span class="timer">Buy it now!!!!!! only <span id="counter">15555</span> left</span>
</body>
I just end up with one timer or the other working, not both firing off
All you need to do is have 2 unique ids for your counters (let's say counter1 and counter2) and then, update those in your count method like that:
<span class="timer">Buy it now!!!!!! only <span id="counter1">15555</span> left</span>
...
<span class="timer">Buy it now!!!!!! only <span id="counter2">12345</span> left</span>
var timer;
var nbCounters = 2;
function startCount() {
timer = setInterval(count, 200); // 200 = 200ms delay between counter changes. Lower num = faster, Bigger = slower.
}
function count() {
// Update all counters
for(i=1; i<=nbCounters; i++) {
var rand_no = Math.ceil(9 * Math.random()); // 9 = random decrement amount. Counter will decrease anywhere from 1 - 9.
var el = document.getElementById('counter' + i);
var currentNumber = parseFloat(el.innerHTML);
var newNumber = currentNumber - rand_no;
if (newNumber > 0) {
el.innerHTML = newNumber;
} else {
el.innerHTML = "Sold Out"; // This message is displayed when the counter reaches zero.
}
}
}
I'd really advise you to have a look at jQuery for DOM manipulation: https://api.jquery.com/
Lucas
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>
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();
}