JavaScript counter - immediately implement comma on page load - javascript

I have a JavaScript counter (that works beautifully) and have now added commas, which works too. The commas show up, BUT it only shows when the counter increments. It's actually 4 counters and a total counter. 3 of the counters increment so often that it's not a problem, but I need the commas to show up on page load as there is a background and not just when the counter increments. I think it has to do with where I call the addCommas(), but can't get it working when I call it differently. I'll throw in some of the code:
var crate_msInterval = crate_interval * 1000;
crate_count = parseInt((now - start_date)/crate_msInterval) * increment + start_value;
document.getElementById('crate_counter').innerHTML = crate_count;
setInterval("crate_count += increment; document.getElementById('crate_counter').innerHTML = addCommas(crate_count);", crate_msInterval);
And then the commas function I'm using:
function addCommas(str){
var arr,int,dec;
str += '';
arr = str.split('.');
int = arr[0] + '';
dec = arr.length>1?'.'+arr[1]:'';
return int.replace(/(\d)(?=(\d{3})+$)/g,"$1,") + dec;
}
I hope I'm being clear enough. Any suggestions?

Just call the function addCommas on page load and set the element innerHTML. Also you can pass an anonymous function to setInterval method instead of specifying the code as a string.
var crate_msInterval = crate_interval * 1000;
var crate_count = parseInt((now - start_date)/crate_msInterval) * increment + start_value;
document.getElementById('crate_counter').innerHTML = crate_count;
setInterval(function(){
crate_count += increment;
document.getElementById('crate_counter').innerHTML = addCommas(crate_count);
}, crate_msInterval);
//This will set the initial value formatted with comma's
document.getElementById('crate_counter').innerHTML = addCommas(crate_count);

In your tag, you can have an onload parameter which invokes the javascript passed to it after the page has loaded.

Related

Making a Javascript that are adding a number to an another number then adding it again to their result and so on

I'm trying to make a script that are adding 10 to 10, then 10 to 20, then 10 to 30, and so on.
I mean, to auto count, by 10 by 10.
The problem is that you are using the ++ operator, witch increments the variable by 1. Just use this:
function init() {
var n = 0;
e = document.getElementById("output");
setInterval(function() { e.innerHTML = n = n + 10; }, 1000);
}
window.onload = init;
You could take instead of an increment operator ++
++n
an addition assignment +=
n += 100
with a fixed value for addition.
For getting a number which has some kind of easing, you could round the number.
function getRound(v) {
var i = Math.floor(Math.log10(v) - 3),
f = Math.pow(10, i);
return Math.round(v / f) * f;
}
function init() {
var n = 0, // declare both
e = document.getElementById("output"); // variables
setInterval(function() {
n += 29979245.8; // increment by the wanted value
e.innerHTML = getRound(n); // assign value to element
}, 100);
}
window.onload = init;
<div id="output"></div>
Gathering from your comments, what you seem to actually want is something like this:
var universe = 0;
show_value();
setInterval(function() {
universe += 299792.458;
show_value();
}, 1);
function show_value() {
display = universe.toFixed(5)
document.getElementById("universe").innerHTML = display + " meters!";
}
This jsfiddle shows what it does. I hope I have understood the effect you were hoping for.
The reason your code wasn't working was because of a cardinal misunderstanding of setTimeout; the second arguement is the number of milliseconds to wait to run the first arguement, your function. You currently have it set to 1000 which is a second, but you want it to run more times a second to give a "eased" effect.
You seem to want to do this in increments of 10, but you'd have to run your function 29979245.8 times a second, or around every 33.35 microseconds. So instead, in my example it runs every millisecond, adding 299792.458 every time instead of 10 to account for that. To make it so that the number doesn't "jump" I also used toFixed.

canĀ“t manage timeouts in for loop in javascript

I'm trying to do some kind of Simon game in javascript. I have already made a table, and a function that changes any cell by its id to another id, so it's color changes for 300 miliseconds. This is the code:
var seleccionarcelda = function(object){
var id=object.id;
object.id="selected";
setTimeout(function(){object.id=id;},300);
}
Then, for a sequence as large as I want it to, it should light a random cell, and then another cell, in a for loop
var secuencia = function(numero){
for(j=0; j<numero; j++){
var cel="t"+ Math.floor((Math.random() * 6) + 1);
console.log(cel);
seleccionarcelda(document.getElementById(cel));
}
}
The problem is that it kind of works, but selects all cells at once, and not in order as it should do. How can I fix it?
You could pass the loop index into the function and use that as a multiplier of the delay time.
Something like:
var seleccionarcelda = function(object, index){
// increment delay timer
var delay = (index + 1) * 300;
var id=object.id;
object.id="selected";
setTimeout(function(){object.id=id;}, delay );// use variable for timer delay
}
var secuencia = function(numero){
for(j=0; j<numero; j++){
var cel="t"+ Math.floor((Math.random() * 6) + 1);
console.log(cel);
// pass j to function
seleccionarcelda(document.getElementById(cel), j);
}
}
What is happening now is the loop completes in milliseconds and therefore all the setTimeout start at basically the same time

Increment Bitcoin Numerif Format Javascript

Hello why i try to coding something like a counter for bitcoin. this is the Code
result: <div id="counter"></div>
This is the Html
This is Javascript Code
var INTERVAL = 1; // in seconds
var INCREMENT = (0.00000001).toFixed(8); // increase per tick
var START_VALUE = (0.00000001).toFixed(8); // initial value when it's the start date
var count = 0;
$(document).ready(function() {
var msInterval = INTERVAL * 3000;
count = INCREMENT + START_VALUE;
document.getElementById('counter').innerHTML = count;
window.setInterval( function(){
count += INCREMENT;
document.getElementById('counter').innerHTML = count;
}, msInterval);
});
Heres the Output you can check
https://jsfiddle.net/8eqc2b3t/
Can anyone help
First of all, I've modified your code a little to make a bit more sense, you're using a few keywords that could be reserved within certain languages, so I'd avoid that in future ( like using count as a variable name )
var interval = 1; // in seconds
var increasePerTick = (0.00000001).toFixed(8); // increase per tick
var startingValue = (0.00000001).toFixed(8); // initial value
var $counter = $('#counter');
var btcAmount = 0.00000000;
$(document).ready(function() {
var msInterval = interval * 1000; // Convert to Milliseconds
$counter.text(startingValue); // Set initial amount
window.setInterval( function(){
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
$counter.text(btcAmount);
}, msInterval);
});
The main issue was that when you were using the + operand you were adding to the string rather than adding the two floats together. You'd also not added jQuery to your Fiddle, causing it not to work, I've fixed this and shown how to do the calculation here too, which basically is to parse both the floats, set them toFixed(8) and then print them to the counter.
The addition part is here:
btcAmount = (parseFloat(btcAmount)+parseFloat(increasePerTick)).toFixed(8);
You were also converting your msInterval incorrectly. Now seconds in interval should work out correctly when changed.
Hope this helps.
Edit:
Forgot to add the Fiddle, sorry! : https://jsfiddle.net/20Lppogq/

Updating numeric variable but getting NaN

I'm trying to update the position of a object in canvas but when I try to add dt to the position I get only NaN.If I try a console log I get NaN and some random numbers.
Even if I try with a simple variable initialized with 0 I get the same NaN stuff
function update(dt) {
player.pos[0] += dt;
player.pos[1] += dt;
gameTime += dt;
console.log(gameTime + " " + dt);
}
jsfiddle
At very fisrt, you are declaring the variable var lastTime; without assging any default value, I think it should be declare something like this.
var lastTime = 0;
The problem is in this line when you do not assign any numeric value to lastTime
var dt = (now - lastTime) / 1000.0;
The problem was with the lastTime variable; You are using it in a arithmetic operation without initializing it first.
Try this
http://jsfiddle.net/NHmDa/1/

Incrementing a number smoothly with a variable time period in JS

I have a really simple JS counter which I display on a dashboard like screen which does the following:
Every 5 minutes it makes an jsonp call and retrieves a "total" number
It then displays this number to the screen by incrementing the last total displayed till it is equal to the new total. (the number can only ever increase)
I'm having some trouble with making the number increment smoothly. What I would like to do is find a delta (i.e. New total - old total) and increment the number gradually over the 5 minutes till the next call so it looks like a nice smooth transition.
Any ideas on how I can do this?
Currently some of my code looks like this (This block get's called every 5mins. And yes, it's in dire need of a refactor...)
var LAST_NUMBER_OF_SESSIONS = null;
var five_minutes_in_seconds = 300;
var new_number_of_sessions;
$.getJSON('http://blah.com/live_stats/default_jsonp.aspx?callback=?', function(data) {
if(LAST_NUMBER_OF_SESSIONS === null){
LAST_NUMBER_OF_SESSIONS = data.total_sessions;
}
new_number_of_sessions = data.total_sessions;
var delta = Math.floor(new_number_of_sessions - LAST_NUMBER_OF_SESSIONS);
var time_interval = (five_minutes_in_seconds / delta) * 1000;
var old_value = LAST_NUMBER_OF_SESSIONS;
var new_value = null;
sessions_interval = setInterval(function (){
new_value = parseInt(old_value, 10) + 1;
$('#stats').text(new_value);
old_value = new_value;
if(new_value >= new_number_of_sessions){
clearInterval(sessions_interval);
}
}, time_interval);
LAST_NUMBER_OF_SESSIONS = new_value;
});
}
This code it seems to increment the number very quickly at the start of the 5min period and then stop so it's not exactly right...
Try this:
var total = 0,
delta = 0,
stats = $('#stats').text( total );
function increment() {
var v = +stats.text();
if ( v < total ) {
stats.text( v + 1 );
} else {
$.getJSON('http://...', function(data) { // added data here
delta = Math.floor( 300000 / ( data.total_sessions - total ) );
total = data.total_sessions;
});
}
setTimeout(increment, delta);
}
Update:
In order to test my code, I had to simulate the JSON reponse - I used an array of numbers. See here: http://jsfiddle.net/simevidas/MwQKM/
(In the demo, I use an interval of 5 seconds instead of 5 minutes.)
I am not exactly sure why your code doesn't work as expected, although I suspect that it has to do with line LAST_NUMBER_OF_SESSIONS = new_value;. I wrote something similar and it works fine. It's not that different from what you have, minus that last line of code.

Categories

Resources