1

Possible Duplicate:
Is JavaScript's Math broken?

I'm having some problems with my loop acting funny, here it is:

var duration = 1000;  /* 1000 millisecond fade = 1 sec */
var steps = 20;       /* number of opacity intervals   */
var delay = 5000;     /* 5 sec delay before fading out */

function fadeOut(eid) {
  for (i = 0; i <= 1; i += (1 / steps)) {
    setTimeout("setOpacity(" + (1 - i) + ",'"+eid+"')", i * duration);
    console.log("i="+i);
  }

}

and I used console.log to check out what's happening on the loop, and it turns out very weird:

i=0
i=0.05
i=0.1
i=0.15000000000000002
i=0.2
i=0.25
i=0.3
i=0.35
i=0.39999999999999997
i=0.44999999999999996
i=0.49999999999999994
i=0.5499999999999999
i=0.6
i=0.65
i=0.7000000000000001
i=0.7500000000000001
i=0.8000000000000002
i=0.8500000000000002
i=0.9000000000000002
i=0.9500000000000003
Community
  • 1
  • 1
skeddles
  • 25
  • 2
  • 1
    Have a look at http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems – Sirko Jun 19 '12 at 13:00
  • `i += (1 / steps)` is not a whole number. – jbabey Jun 19 '12 at 13:02
  • 1
    **Never** pass a string to `setInterval()` or `setTimeout()`. Doing so is as bad as using `eval()` and it results in unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable. The proper solution is `setInterval(function() { /* your code *) }, msecs);`. The same applies to `setTimeout()`. If you just want to call a single function without any arguments, you can also pass the function name directly: `setInterval(someFunction, msecs);` (note that there are **no** `()` behind the function name) – ThiefMaster Jun 19 '12 at 13:03
  • Do you want to know why this is happening or how to fix it? – Jeff Jun 19 '12 at 13:07
  • So you suggest using `setTimeout(function() { setOpacity(1 - i, eid); }, i * duration);` right? that seems to not work – skeddles Jun 19 '12 at 13:21

1 Answers1

2

Those are the actual floating point values. You might want to round them for display purposes.

console.log("i="+i.toFixed(2));

http://www.mredkj.com/javascript/nfbasic2.html

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126