user2906759
user2906759

Reputation: 831

Can the mousedown event happen in the middle of a loop?

I'm trying to figure out how events that are triggered by user actions happens exactly.

In the following example, can the event ever happen in between the two functions causing only the second function to execute?

var mouseDown = false;

element.addEventListener('mousedown', function(evt) {
    mouseDown = true;
}, false);

function loop() {
    doSomething();

    // Can mouseDown be set to true here?

    doSomethingElse();

    mouseDown = false;

    requestAnimationFrame(loop);
}

function doSomething() {
    if (mouseDown) {
        // Do something
    }
}

function doSomethingElse() {
    if (mouseDown) {
        // Do something else
    }
}

Can this happen or is the event deferred to between loop rounds?

Upvotes: 1

Views: 73

Answers (1)

Guffa
Guffa

Reputation: 700382

No, that can never* happen.

Javascript event handling is single threaded, which means that no events are ever handled as long as your code is running.

When you exit the function (loop) and return control to the browser, event handling can resume.


(*) The exception would be if you have a dialog like an alert in that code, then some events may be handled, in some browsers.

Upvotes: 1

Related Questions