I've a asynchronous forEach looping through an array
var anArray = [.....values inside...];
anArray.forEach(function (s) {
...
});
And also a 2 global variables that will be updated:
var count = 0;
var total = 0;
During the foreach, I'll be updating both variables. As the foreach is async, I might expect multiple iterations to be running at the same time. Which means that that my variables might be over written.
For count
, it's fine as all I'm doing is a count++ in each loop.
However for total
, different values will be added during each look.
Is there anyway for me to ensure that total
will be updated without any loss of precision??
total
is built up which can cause precision issues, i.e,a + b + c
orc + b + a
? – pimvdbc=a+b
then at the same time, af=a+c
. Then the addition of eitherb
orc
might not be captured. – tommiforEach()
takes a callback function as a parameter, but there are lots of synchronous functions that do that. If you're not usingsetTimeout()
,setInterval()
or an ajax function then chances are you're not dealing with asynchronous code. If you wrote your own async "loops" usingsetTimout()
then you could theoretically have issues with more than one block of code updating the same variables (even though non web-worker JS executes on only one thread). – nnnnnn