1

I have an click event handler that dequeues a function if one is available. I made a loop to wait for the queue. I thought this would work but on one of my machines it results in a busy wait and freezes everything. I'm confused about why this is a problem. The goal is to wait for the queue to be non-empty. Can anyone help? Thanks

function handleViewClick(event){
  clickEvent = event;  // make event details available to requestReport on body-foo Q
  var body = $("body");
  while ( 0 == body.queue("foo").length ) 
    setTimeout(function(){
        handleViewClick(event);
      },
      1000);
  body.dequeue("foo");  // analyze and report on click.
}

1 Answer 1

4

Let me put your code in English, see if it helps.

  • The handleViewClick function, which takes an event...
    • Assigns event to the clickEvent variable
    • Gets the document body and puts it in body
    • If the length of the queue foo is non-zero...
      • Set a timer to call handleViewClick again in one second
    • If the length of the queue foo is non-zero...
      • Set a timer to call handleViewClick again in one second
    • If the length of the queue foo is non-zero...
      • Set a timer to call handleViewClick again in one second
    • If the length of the queue foo is non-zero...
      • Set a timer to call handleViewClick again in one second
    • ...
    • Crash.

while loops will run until completion. setTimeout will run when it gets an opportunity, as soon as possible after the time specified. The two are incompatible. You are setting millions of timers and expecting the result to be different.

Did you mean if instead of while? Because that would work, if you then put the dequeue call in the corresponding else.

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

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.