In the javascript program below (Euler problem 5) I am practicing writing asynchronous / non blocking function. The program is trying to find the smallest number evenly divisible by numbers 1-10. 2520 is the first smallest and that is where the program should stop.
I set up the program so that if the functions run together, then the second checkNum should be done first and print the second one first, then the first one, but that is not happening?
How can I get the function to run at the same time, instead of one after another? I am expecting the callback from the second checkNum function I call to be called first (since it starts closer to the answer), then the first, but that is not what happens. Thanks so much!
var divides = function(a, b) {
return b % a == 0;
};
function checkNum(counter, callback) {
var noRemainder = 0;
var forward = true;
while (forward)
{
for (var i = 1; i <= 10; i++) {
if (divides(i, counter))
{ noRemainder++; }
}
if (noRemainder == 10) {
console.log(counter);
forward = false;
callback(counter);
} else {
console.log(noRemainder);
noRemainder = 0;
counter++;
console.log(counter);
}
}
}
checkNum(1, function(counter) {
setTimeout(function(){
console.log("The counter is: " + counter)},3000)
}
);
checkNum(2500, function(counter) {
setTimeout(function(){
console.log("The counter2 is: " + counter) },3000)
}
);