I understand that because of Javascript's single-threaded execution, long loops or recursive calls could make the browser unresponsive while they execute.
I thought about simulating recursion using setTimeout
with a delay of 0, so as to queue the next call to execute as soon as possible.
Here's an example comparing a standard recursive factorial function with an attempt to do the same thing but using setTimeout
:
function rFactorial(num)
{
if (num === 0) return 1;
else return num * rFactorial( num - 1 );
}
function tFactorial(num, callback, acc) {
acc = acc || 1;
if (num === 0) {
callback(acc);
}
else {
setTimeout(function() {
tFactorial(num-1, callback, acc*num);
}, 0);
}
}
I tested this using the following test:
for (var x = 1; x < 20; x += 1) {
tFactorial(x, (function(n) {
return function(result) {
console.log(rFactorial(n) === result)
};
})(x));
}
This worked for that range of numbers, although for higher numbers the two functions seem to give different results. for example, for 100, sFactorial
gives 9.332621544394418e+157
, while rFactorial
gives 9.33262154439441e+157
.
So I have two questions. (1) Is this a good approach, can anyone suggest any improvements etc. (2) can anyone shed any light on why the two functions give the same results for lower numbers but different results for higher numbers?