Number counter issue - javascript

I have been searching the entire day for a solution to this problem. I like this Counter I found on StackOverflow, but because I am inexperienced using JavaScript, I am not entirely sure how to stop it.
I figured out how to set the value and when to start counting etc, but now I want to add a maximum value. IE: If the counter reaches 20 million, then stop.
I tried the following, but it doesn't work:
var simplicity = formatMoney(20000000);
if (amount.innerText <= simplicity){
function update() {
var current = (new Date().getTime() - start)/1000*0.36+0;
amount.innerText = formatMoney(current);
}
setInterval(update,1000);
}
else{
amount.innerText = simplicity;
}

Try this
var max = 20000000;
var intervalId = setInterval(function () {
var current = (new Date().getTime() - start)/1000*0.36+0;
if (current > max) {
amount.innerText = formatMoney(max);
clearInterval(intervalId);
} else {
amount.innerText = formatMoney(current);
}
}, 1000);
Use clearInterval(id) to stop intervals.

Related

Playing animation during x seconds using setInterval

I want to display an animated number from 0 to max value y during x seconds. I have tried this following code but it take too much to complete and clear the interval.
jQuery('.numbers').each(function(item, index) {
const $obj = jQuery(this);
let objValue = parseInt($obj.text()),
currentValue = 0,
speed = 1,
time = 4000,
step = Math.floor(objValue / time);
$obj.text(currentValue);
let interVal = setInterval(() => {
if (currentValue >= objValue) {
clearInterval(interVal);
$obj.text(objValue);
}
$obj.text(currentValue);
currentValue += step
}, speed);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>
How do I play this animation during exactly time seconds?
It is better not to depend on the timing of setInterval(), but the real problem in your script is that you use the floored value to decide the new value to print out.
It is better to use Window.requestAnimationFrame() and create a update() function that prints the current number based on the real time elapsed.
let start, previousTimeStamp;
let numbers = document.querySelectorAll('.numbers');
requestAnimationFrame(update);
function update(timestamp) {
if (start === undefined) {
start = timestamp;
}
const elapsed = timestamp - start;
[...numbers].forEach(elm => {
if(!elm.dataset.start){
elm.dataset.start = elm.textContent;
}
let start = parseInt(elm.dataset.start);
elm.textContent = Math.floor(start / 4000 * elapsed);
});
if (elapsed < 4000) {
previousTimeStamp = timestamp;
requestAnimationFrame(update);
}else {
start = undefined;
[...numbers].forEach(elm => {
elm.textContent = elm.dataset.start;
});
}
}
<span class='numbers'>7586</span>
<span class='numbers'>147520</span>

Function that displays variable numbers from last minute

I am trying to make a function that will only retain its variable count from the past minute.
For example, if I call function count 100 times, if 60 of those calls were from the past minute, it will only return 60, and not 100.
This is what I have tried so far, making the variable an array and adding numbers to it everytime its called, but I do not know how to remove a count when a minute has passed.
var count = 1;
var countArray = [];
UPDATE:
I have updated my code with this, but the array elements are not removing as they should,
function Count() {
var jNow = new Date();
jCountArray.push(jNow);
for (var i = 0; i <= jCountArray.length; i++) {
var secondsDiff = (new Date(jNow).getTime() - new Date(jCountArray[i]).getTime()) / 1000;
if (secondsDiff >= 10) { jCountArray.shift(); }
}
console.log(jCountArray);
return jCountArray.length;
}
If I understand your requirements correctly, and the only thing you need Count to do is return how many times it was called in the last minute, I think we could do something relatively easily leveraging setTimeout:
function getCounter() {
let count = 0;
let duration = 60000;
return function () {
count = count + 1;
setTimeout(function () {
count = count - 1;
}, duration);
return count;
}
}
let counter = getCounter();
function count() {
console.log(counter());
}
<button onclick="count()">Count</button>
The only trick here is, to keep the actual count private, we need a factory function to wrap it in a closure. If that's unimportant you can write it as a simple function and keep the count in the parent scope. Also, for testing purposes you can change the duration to a lower millisecond count to see it in action.

Javascript 30 second console count down timer

I am interested in creating a basic countdown timer in the console of Javascript. My code needs to countdown from 30 and must stop at 0. I have worked through some code but for some reason it is not working. I am a noob at Javascript (First programming language and only been doing 5 weeks). Please help. Below is my code so far.
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i <= 0) {
clearTimeout(countdownTimer);
}
}, 1000);
}
startTimer();
Thanks for the help! :)
You need to clear interval, not timeout since you are using setInterval for your timer:
var i = 30;
function startTimer() {
var countdownTimer = setInterval(function() {
console.log(i);
i = i - 1;
if (i <= 0) {
clearInterval(countdownTimer);
}
}, 1000);
}
startTimer();

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.

Simple jQuery Count Up timer help please

Trying to make a simple count up timer in jQuery... this sort of works but is adding the numbers to the end of '0000' and I want it to go '0001' '0002' '0003' etc...
This is all happening in the jQuery onReady scope.
var i = '0000'
var timer = function doSomething ( )
{
i = i+= 1
$('.counter').text(i);
console.log(i);
}
setInterval (timer, 1000 );
Your "i" variable needs to be an integer. You can format it how you like when you want to print it somewhere.
$(document).ready(function() {
var i = 0;
var target = $('.counter');
var timer = function doSomething ( )
{
i++;
var output = pad(i,4);
target.text(output);
console.log(output);
}
setInterval (timer, 1000 );
});
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}​
Your current code is appending to a string, not addition to a number. It essentially looks like
i = '0000' + 1, i = '00001' + 1, i = '000011' + 1 ...
and so on. You'll need to keep it integer based to continue adding to the number. Here's an example with the formatting it looks like you wanted.
var pad = function(n) { return (''+n).length<4?pad('0'+n):n; };
jQuery.fn.timer = function() {
var t = this, i = 0;
setInterval(function() {
t.text(pad(i++));
}, 1000);
};
$('#timer').timer();
http://jsfiddle.net/jDaTK/
I would do something more like this:
// Make sure Date.now exists in your environment
Date.now = Date.now || function () { return Number(new Date()); };
var time = 0,
start = Date.now(),
intervalId;
intervalId = setInterval(function () {
var seconds, display;
// get the exact time since the timer was started
time = Date.now() - start;
// get the number or seconds, rounded down
seconds = Math.floor(time / 1000);
display = '' + seconds;
// pad the beginning of your display string with zeros
while (display.length < 4) {
display = "0" + display;
}
console.log(display);
}, 100);
setInterval is not exact. This code ensures that while the display could be up to nearly a second off (in theory), the actual time you are tracking is always the exact amount of time that has elapsed since you started the timer. But this code would update the display about once every tenth of a second, so it's not likely to ever be off more than a few milliseconds.
From here you can figure out smarter ways to update the display to ensure you have the level of accuracy you need. If this needs to be pretty accurate, then you could make sure you are displaying to the tenth of the second.
I really recommend the jQuery CountUp plugin. I tried a number of Javascript counters and this was one of the easiest to implement and came with lots of goodies:
<script type="text/javascript">
$(document).ready(function(){
$('#counter').countUp({
'lang':'en', 'format':'full', 'sinceDate': '22/07/2008-00::00';
});
});
</script>
<div id="counter"></div>

Categories