Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript deadlock

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?

like image 441
Ikrom Avatar asked Oct 15 '25 08:10

Ikrom


1 Answers

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.

like image 116
Denys Séguret Avatar answered Oct 16 '25 22:10

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!