How to setup Multiple countdown timers on products? - javascript

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

Related

Trying with JavaScript to achieve it but something seems to be wrong with the script

The goal is to make the button turn off if pressed 10 times in less than 1 minute but keep counting if not pressed 10 times in 1 minute? so only disables when pressed 10 times in less than 1 minute. You can click nine times in a minute but nothing happens but the tenth time the button turns off, but if the minute has passed you can keep clicking but always for a maximum ten times and the counter does not reset but continues to increase in number.
let accCounter = 0;
let totalCount = 0;
document.getElementById('totalCounter').innerText = totalCount;
document.getElementById('clap').onclick = function() {
const clap = document.getElementById('clap');
const clickCounter = document.getElementById("clicker");
upClickCounter();
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
}
var endCount = 5; // 5 for testing - this would be 10
var interval = 5000 // 5s for testing, 1 min= 1000 * 60;
var clicks = [];
var totalClicks = 0;
$("#btn").click(function() {
clicks.push(Date.now());
totalClicks++;
checkIt();
})
function checkIt() {
//if (clicks.length < endCount) return;
while (clicks.length && (Date.now() - clicks[0]) > interval) {
console.log("removing: " + ((Date.now() - clicks[0]) / 1000))
clicks.shift();
}
if (clicks.length < endCount) return;
$("#btn")[0].disabled = true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="clap" class="clap-container"></button>
<div id="totalCounter" class="total-counter"></div>
<div id="clicker" class="click-counter"></div>

Increase a number based on Date or Interval javascript (and keep it after refresh page)

I'm struggling for while trying to figure out how to increase a number based on a Date or based on a time (Using setInterval).
I don't know which option is easier. I made it by using setInterval:
HTML
<p class="counter"></p>
JS
let tickets = 35000;
const counter = document.querySelector('.counter');
let interval = setInterval(function(){
console.log(tickets);
if (tickets >= 60000) {
var textSoldOut = `<p>¡Todo vendido!</p>`;
counter.innerHTML = textSoldOut;
console.log("Sold out");
clearInterval(interval);
}else{
var text = `¡${tickets} tickets Sold!`;
contador.innerHTML = text;
console.log(text)
}
const random = Math.floor(Math.random()*(200-100+1)+100);
tickets += random;
}, 10000);
The thing is every time the page is refreshed the counter starts from 35000 again. I am trying to figure out how to storage the var tickets. I guess this would be made by using localStorage, but since I am a beginner in JS, I am not able to do it.
Other option would be by checking the date, and based on that, show a number:
function date() {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
const counter = document.querySelector('.contador');
const random = Math.floor(Math.random()*(200-100+1)+100);
for (let i = 350000; i <= 60000 ; i++) {
if (month == 0 & day == 28) {
var sum = i + random;
document.getElementById("contador").innerHTML = suma;
}else if (mes == 0 & dia == 30) {
...
} else if (...){
...
}
}
document.getElementById("dia").innerHTML = dia;
document.getElementById("mes").innerHTML = mes;
}
fecha();
Could someone help me out to reach the result?
I would really appreciate it
The Storage object accessible via the localStorage property offers two methods to save or retrieve data: setItem and getItem().
Usage is quite simple. If you want to save the numbers of tickets into a myTickets key on localStorage you have to do it like this:
localStorage.setItem("myTickets", tickets);
To retrieve that data later on:
localStorage.getItem("myTickets");
You just have to make sure to update the myTickets key on localStorage as you increase the number of tickets inside the setinterval callback function.
let tickets = 35000;
if (localStorage.getItem("myTickets") == null) {
localStorage.setItem("myTickets", tickets);
} else {
tickets = localStorage.getItem("myTickets");
}
const counter = document.querySelector('.counter');
let interval = setInterval(function() {
console.log(tickets);
if (tickets >= 60000) {
var textSoldOut = `<p>¡Todo vendido!</p>`;
counter.innerHTML = textSoldOut;
console.log("Sold out");
clearInterval(interval);
} else {
var text = `¡${tickets} tickets Sold!`;
console.log(text)
}
const random = Math.floor(Math.random() * (200 - 100 + 1) + 100);
tickets += random;
localStorage.setItem("myTickets", tickets);
}, 10000);

Delay between a loop using javascript or jquery for a multiple number counter

I have been trying to create a number counter using javascript and jquery. I want 2 counters where one depends on the other.
I want a counter to increment from 0-2000 with an interval of 100 milliseconds between increments. and whenever one counter reaches an multiple of 200(num=200 or num=400 or num=600...) the other counter increments by one. The result expected is a counter goin from 0-2000 and another going from 0-10 in the same amount of time.
This a code snippet I have failed to get the result with:
html code:
<span id="counter" >0</span>
<span id="counter2" >0</span>
javascript code:
function counting(){
var cc=0;
for(var c=0;c<2000;c++){
if((c % 200) === 0){
$('#counter2').text(cc+1);
}
else{
setTimeout(function(){$('#counter').text(c);},100);
}
}
}
Please help me out with any javascript or jquery solution..
Using setInterval is better suited here. Also, you should increment cc by 1 and store it in cc itself.
function counting() {
var cc = 0,
c = 1;
var int = setInterval(function() {
$('#counter').text(c);
if (c % 200 === 0) {
cc += 1;
$('#counter2').text(cc);
}
if (c >= 2000) {
clearInterval(int);
}
c += 1;
}, 1);
}
counting();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="counter">0</span>
<span id="counter2">0</span>
I've modified the interval to 1ms for this demo. You may change it as per your requirements.
Best to use setInterval with conditions inside the interval function, followed by a clearInterval at the end. No need for jQuery:
const counter = document.querySelector('#counter');
const counter2 = document.querySelector('#counter2');
let count = 0;
const interval = setInterval(() => {
count++;
counter.textContent = count;
if (count % 200 === 0) counter2.textContent = count / 200;
if (count === 2000) clearInterval(interval);
}, 100);
<span id="counter" >0</span>
<span id="counter2" >0</span>
A sped-up version:
const counter = document.querySelector('#counter');
const counter2 = document.querySelector('#counter2');
let count = 0;
const interval = setInterval(() => {
count++;
counter.textContent = count;
if (count % 200 === 0) counter2.textContent = count / 200;
if (count === 2000) clearInterval(interval);
}, 10);
<span id="counter" >0</span>
<span id="counter2" >0</span>

Make number grow with jQuery using same amount of time for every number

My goal is to perform a jQuery script that'll make any number visually grow from zero until its value with setInterval().
Here's what I came up with:
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var refresh = 5;
var start = 0;
var step = 1;
var interval = window.setInterval(function() {
start += step;
$el.text(start);
if(start >= max)
clearInterval(interval);
}, refresh);
});
My problem is I have numbers ranging from a few hundreds to several hundreds thousands. With this script, bigger number take more time to reach their value.
My goal is to make any number, regardless of its goal value, take the same amount of time to reach it. I sense that I should divide the number by the number of seconds I want the animation to run and then, set the result as the interval step?
I'm inquiring but still seeking for help :)
Thanks.
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var duration = 1000; // shared duration of all elements' animation
var refresh = 5;
var frames = duration / refresh; // number of frames (steps)
var start = 0;
var step = Math.max(Math.round(max / frames), 1); // step should be >= 1
var interval = window.setInterval(function() {
if(start + step < max) {
start += step;
}
else {
start = max;
clearInterval(interval);
}
$el.text(start);
}, refresh);
});
This should work I suppose,
$('.grow').each(function() {
var $el = $(this);
var max = parseInt($el.text().replace(/\s/g, ''));
var start = 0;
var refresh = 5;
var totalSteps = 10;
var step = max/totalSteps;
function calculate(){
start += step;
$el.text(Math.round(start));
if(start < max){
setTimeout(function() {
calculate();
}, refresh);
}
}
calculate();
});
This will always finish in 100 steps. I.e. 100*refresh = 100*5 = 500 seconds.

Inefficient javascript countdown timer

I have created a very simple countdown timer in js which every element of time is calculated out. It works, the only issue with it is there exists lag most likely caused from the calculations being made every second. Any thoughts as to how to make this more efficient?
js:
var count = 55010; //needs to be in seconds
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer(){
count = count-1;
if (count <= -1){
clearInterval(counter);
return;
}
document.getElementById("hour10").innerHTML=Math.floor(((count/86400)%1)*2.4);
document.getElementById("hour1").innerHTML=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10;
document.getElementById("min10").innerHTML=Math.floor(((count/3600)%1)*6);
document.getElementById("min1").innerHTML = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10;
document.getElementById("sec10").innerHTML = Math.floor(((count/60)%1)*6);
document.getElementById("sec1").innerHTML = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10;
}
HTML:
<span id="hour10">0</span>
<span id="hour1">0</span> :
<span id="min10">0</span>
<span id="min1">0</span> :
<span id="sec10">0</span>
<span id="sec1">0</span>
The reason I have created the timer in this fashion is because I want to put each element into a div container like so:
Thanks in advance!
A way to make this more efficient is to keep a reference to the elements by only searching the Dom once, and also use innerText if you are not using any markup
var count = 55010; //needs to be in seconds
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
var elHour10 = document.getElementById("hour10");
var elHour1 = document.getElementById("hour1");
var elMin1 = document.getElementById("min10");
var elSec10 = document.getElementById("sec10");
var elSec1 = document.getElementById("sec1");
function timer(){
count = count-1;
if (count <= -1){
clearInterval(counter);
return;
}
elHour10.innerText=Math.floor(((count/86400)%1)*2.4);
elHour1.innerText=Math.floor(((count/86400)%1)*24)-(Math.floor(((count/86400)%1)*2.4))*10;
elMin10.innerText=Math.floor(((count/3600)%1)*6);
elMin1.innerText = Math.floor(((count/3600)%1)*60)-(Math.floor(((count/3600)%1)*6))*10;
elSec10.innerText = Math.floor(((count/60)%1)*6);
elSec1.innerText = Math.floor(((count/60)%1)*60)-(Math.floor(((count/60)%1)*6))*10;
}

Categories