问题
Here I saw JavaScript deadlocks and this code:
var loop = true,
block = setTimeout(function(){loop = false}, 1);
while(loop);
It's definitely infinite loop and causes to browser freezing. It's said that deadlock is created when one operation wait another one to be executed and vice-versa
.
My question is, except that, what kind of situations deadlock occurs and the ways to avoid them?
回答1:
That's not a deadlock, just an infinite loop, you can't have a deadlock in JavaScript as you can't have more than one thread accessing your data.
What happens here is that as your loop never ends and the js engine being mono-thread (regarding your script), the scheduler never calls the callback you give to setTimeout
. In fact you would have had exactly the same behavior without the second line.
来源:https://stackoverflow.com/questions/16530177/javascript-deadlock