Reputation: 41
It is impossible to run callback function while recursive function is running?
It is sample code of reculsive fibonacci function and setInterval()
'use strict';
function fibo(x) {
if (x === 0) {
console.info('fibo( ' + x + ' ) == 0');
return 0;
} else if (x === 1) {
console.info('fibo( ' + x + ' ) == 1');
return 1;
}
return fibo(x-2) + fibo(x-1);
};
fibo(10);
setInterval(() =>{console.info('hello')},10);
Excuting this code, setInterval run after fibo(10) finished its work.
How to display 'hello' log while fibo() is running? Is it possible to cut in callback function while recursive function is running?
Upvotes: 1
Views: 64
Reputation: 1074595
How to display 'hello' log while fibo() is running?
Since fibo
is synchronous, you can't in the normal case. JavaScript works on the basis of threads servicing a job queue. While one job is running, no other jobs can run on that thread (such as the ones queued by setInterval
to call your callback). There's only one thread per realm (loosely, global environment), and there's only one main thread in all major environments (including browsers). You can create others, but they have their own environment.
You have a couple of options:
fibo
asynchronous, where each call to it schedules the next in another job (via setTimeout
for instance).fibo
a generator function, and call it repeatedly for the values, interspersing those calls with your setInterval
callback.Since your setInterval
code and your fibo
code don't share any data, using a worker thread makes sense:
main.js
:
'use strict';
function fibo(x) {
if (x === 0) {
console.info('fibo( ' + x + ' ) == 0');
return 0;
} else if (x === 1) {
console.info('fibo( ' + x + ' ) == 1');
return 1;
}
return fibo(x-2) + fibo(x-1);
};
new Worker("worker.js");
fibo(10);
worker.js
:
setInterval(() =>{console.info('hello')},10);
If they shared data, you might use shared memory for it, but beware of synchronization issues.
Upvotes: 2