I think I have a misunderstanding of what setTimeout
does exactly in JavaScript. I have this script:
function recursiveFibonacci(n) {
if ( n === 0 ) {
return 1;
} else if ( n === 1 ) {
return 1;
} else {
return recursiveFibonacci(n-1) + recursiveFibonacci(n-2);
}
}
setTimeout( () => {console.log("one second");}, 1000);
console.log(recursiveFibonacci(42));
What I would expect to happen is that recursiveFibonacci starts chugging away on the 43rd value in the Fibonacci sequence. This takes about 4 seconds on my computer. So, after 1 second of work the evaluation would be interrupted and the console would log:
one second
and then about 3 seconds later log:
433494437
Instead what happens is that, after 4 seconds, the console logs:
433494437
one second
all at once. Why is this the case? How can I get setTimeout
to work? Is it the case that the JavaScript interpreter is not actually interrupted by setTimeout
but rather if it finishes its other jobs then it will wait until the given amount of time has passed before calling the given function?
Edit:
I found this tool very useful for understanding the relevant concepts: