Updating numeric variable but getting NaN - javascript

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/

Related

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/

Function Returns NaN

I am trying to find the distance between two points.
This is my distance function.
var distance = function(first, second) {
var midValue = first - second;
midValue *= midValue;
return Math.sqrt(midValue);
}
This is where I call the distance function.
xDist += distance(locations[i].x, students[j][0]);
When I look at the xDist's value i get NaN. I have implicitly looked the values of locations and students they are all numbers. Also, in the distance function I have looked the value of Math.sqrt(midValue) before I return it and it is a number.
My guess is that locations[i].x or/and students[j][0] is/are undefined because arithmetic operations on undefined or, maybe they are not numbers in the first place, and thus always output NaN
You need to assign a initial value of xDist=0 else it would be undefined.
undefined+10= NaN
you can try this
var distance = function(first, second) {
var midValue = first - second;
midValue *= midValue;
return Math.sqrt(midValue);
}
var xDist=0;
xDist += distance(locations[i].x, students[j][0]);
alert(xDist);
Though it seems number it might not be number always. So better do a parseInt.
var distance = function(first, second) {
var midValue = parseInt(first) - parseInt(second);
midValue *= midValue;
return Math.sqrt(midValue);
}

Javascript Wrong Calculations When Storing Value In A Variable or Object

I am trying to animate related columns' width in my HTML layout using a slider.
in this code everything works great, here I am getting new value for another column on slide-UP.
var item.thisWidth; // current width of edited column
var item.prevCellWidth; // current width of previus/last column
fdd
if(slider.value > item.thisWidth){
var prevNewWidth = item.prevCellWidth - (slider.value-item.thisWidth);
$('#r'+item.thisRowId+'s'+item.prevCellRowOrder+'').css('width', prevNewWidth + '%');
}
But here is something weird happening after the calculation on slide-Down. The value created is in 100s of thousands.
Need to keep in mind that the slider min/max value is from 0-100
"slider.value"
if(slider.value < item.thisWidth){
var prevNewWidth = item.prevCellWidth + (item.thisWidth - slider.value);
$('#r'+item.thisRowId+'s'+item.prevCellRowOrder+'').css('width', prevNewWidth + '%');
}
I have tried to check all values that are being passed over for calculation and they show up ok.
alert('oldWidth'+item.thisWidth+'sliderWidth'+slider.value+'previuscell'+item.prevCellWidth+'');
But when decreasing the slider I get these wrong results
e.g. 30 + (40 - 10) = 400000; ??
UPDATE:
Sorted this out by using #rogelio's suggestion - parsing a string into an integer:
var integer = parseInt(string);
Thanks, #rogelio!
The problem is because slider.value is a string. Assuming that you are getting the value from an input, you will need to parse it to integer. with javascript is trivial, for example your line
var prevNewWidth = item.prevCellWidth + (item.thisWidth - slider.value);
needs to change to
var prevNewWidth = item.prevCellWidth + (item.thisWidth - parseInt(slider.value));
I study my self, so for simple things like that sometimes I can spend a while without having someone to direct me to the right information.
parseInt(value); here is my updated question and answer:)
function handleSliderChange(event, slider){
$('#r'+item.thisRowId+'s'+item.thisRowOrder).css('width', slider.value + '%');
var sliderValue = parseInt(slider.value);
var oldValue = item.thisWidth;
var oldPrevValue = item.prevCellWidth;
if(sliderValue > oldValue){
var prevNewWidth = oldPrevValue - (sliderValue-oldValue);
$('#r'+item.thisRowId+'s'+item.prevCellRowOrder).css('width', prevNewWidth + '%');
}
if(slider.value < item.thisWidth){
var prevNewWidth = oldPrevValue + (oldValue - sliderValue);
$('#r'+item.thisRowId+'s'+item.prevCellRowOrder).css('width', prevNewWidth + '%');}
if(slider.value === item.thisWidth){
var prevNewWidth = sliderValue;
$('#r'+item.thisRowId+'s'+item.prevCellRowOrder).css('width', prevNewWidth + '%');
} }
So for guys like me who is not at uni or college ... always create vars for values, in case of numbers also add parseInt(value) --> that should let you avoid common mistakes and save some time:)

Calculate in Javascript not working

I want to calculate in Javascript but having Strange Problems.
It just adds an 1 to my String but it should calculate it. I am converting my Strings to Int with the parseInt() Function and a am calculating like this: sec = sec + 1;
var calc= parseInt($(this).find("input[name=calc]").val());
calc = calc + 1;
Your string must not be empty if don't want NaN. First check if you get an empty string:
var cal = null;
if ( $(this).find("input[name=calc]").val() ) {
cal = parseInt( $(this).find("input[name=calc]").val(), 10 );
cal++;
}
if(!!sec){
sec = parseInt(sec, 10) + 1;
alert(sec);
}
Or, in your scenario:
var fieldvalue = $(this).find("input[name=calc]").val(), calc;
if(!!fieldvalue){
calc = parseInt(fieldvalue, 10);
calc += 1;
alert(calc);
}
Do you have more code to express. It may just be coming out to 1, because sec is not set as a number
In javascript, the + operator is used for addition and concatenation of strings.
As javascript is weakly typed, you have to add information about the type. Here are two solutions:
Substract 0 from the string
sec = (sec-0) + 1;
Add unary + operator to the string
sec = (+sec) + 1;

JavaScript counter - immediately implement comma on page load

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.

Categories

Resources