JavaScript deadlock

ⅰ亾dé卋堺 提交于 2020-01-14 04:14:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!