Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

197
Views
How to safely send message to a running function in javascript

I tried to work this code:

var foo=0
window.onmouseup=function(){
    foo=1
}
window.onmousedown=function(){
    while(foo==0);
    console.log("bar")
}

the "bar" is not shown and the browser (I use Edge) stuck there(unable to close the page), I had to use Ctrl+T and then Ctrl+W

I guess the problem is foo==0 is optimized, so it reads from the cache, but I don't know how to avoid it. Or are there other methods?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could use setInterval() and put the if statement and the rest of the code in there:

var foo = 0
window.onmouseup = function() {
  foo = 1
}
window.onmousedown = function() {
  var interval = setInterval(() => {
    if (foo !== 0) {
      clearInterval(interval);
      console.log("bar")
    }
  });
}

about 4 years ago · Juan Pablo Isaza Report

0

Actually, I think the problem is that your while loop will just continue running until it "breaks", or ends the loop. However, foo will always be 1 and never 0 after mouseup, therefore the program gets stuck in the while loop forever, and no other tasks on the browser including the important ones get run.

TL:DR program stuck on while

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!