JavaScript死锁 [英] JavaScript deadlock

查看:109
本文介绍了JavaScript死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处我看到了JavaScript死锁和以下代码: / p>

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?

推荐答案

不是死锁,只是一个无限循环,JavaScript中不能有死锁,因为您不能有多个线程来访问数据。

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.

这里发生了什么是因为您的循环永无止境,并且js引擎是单线程的(关于脚本),所以调度程序永远不会调用您提供给 setTimeout 的回调。实际上,如果没有第二行,您的行为将完全相同。

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.

这篇关于JavaScript死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆