kay am see
kay am see

Reputation: 988

Blocking call in javascript

Is it a good idea to write a blocking call in javascript ? Meaning a function that does something for x seconds and returns ?

I wanted to add artificial delays by adding these inline blocking functions.

Downside of doing this is that the CPU is very busy executing some random stuff for x seconds.

Another downside is that the multiple tabs in the browser might hang.

Is there a better way to do this ???

Upvotes: 0

Views: 483

Answers (2)

Ray Toal
Ray Toal

Reputation: 88378

If I understand your question correctly from your comments made to the other answerers, you want to simulate a "thread" that does something, then blocks for a time, then resumes. During the time this "thread" is "blocked," (1) other tabs are active, and (2) the CPU is not busy-waiting.

If this is the case, you can use setTimeout (as Greg Hewgill pointed out). The trick is to think about it as follows. Break up your "thread" into two parts:

DO_FIRST_PART
setTimeout(function () {DO_SECOND_PART}, 5000);

Now you have simulated a thread with a 5 second delay in the middle.

Of course other events on this tab or process will still be accepted. But as Greg pointed out, they should be.

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992717

No, it is not a good idea to do this (you have mentioned some reasons why). Use setTimeout instead.

Upvotes: 3

Related Questions