0

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 ???

1
  • Not sure how many seconds you want to delay for, but if it's too long most modern browsers will display a message to the user telling them there is a slow-running script and asking if they want to cancel it. I assume you don't want that. Commented Oct 18, 2011 at 7:32

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

setTimeout would not work in my use case as it would not block code execution.
I'm afraid you will need to reevaluate your use case. Blocking a browser is not a good idea.
My use case is simple : I am trying to push the onLoad event artificially, by putting these inline blocking calls.
Can you elaborate on what it means to "push the onLoad event"?
push onLoad event : e.g. lets say a normal onLoad fires around 2 seconds, I want it to fire at 5 seconds with 3 seconds of delay ( artificially induced )
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.