javascriptc#.netdom-eventswatin

Can IE execute two JavaScript functions concurrently


We are using WatiN from C# to interact with a browser (currently only IE).

Some of WatiN's methods are a simple wrapper that sends an onchanged() and onclick() to certain web elements.

WatiN also provides a fire-and-forget version for this, which basically provides a non blocking version.

My question is, does the browser also two JS functions to execute at the same time?

For example, assume the following code:

// Uses FireEventAsync("onchanged")
SelectList.SelectNoWait()

SelectList.FireEventAsync("onclick")

Can both JS functions onclick and onchanged execute at once?

I believe we are experiencing a similar issue, where an onchanged() function is still executing while we fire another event, I was wondering if that is technically possible.


Solution

  • In short: no. JavaScript execution is single-threaded.

    However, with asynchronous operations (ajax, timers, workers, etc.), parts of a function can be setup to be executed later when the thread is free.

    A contrived example would be:

    function foo() {
        setTimeout(function () {
            console.log('three');
        }, 10);
    
        console.log('one');
    }
    
    function bar() {
        console.log('two');
    }
    
    foo();
    bar();
    

    Though foo and bar are called synchronously and the logs are written in order of three, one, two, they will be executed in order of one, two, three as the timer will delay the log of 'three' for later.

    And, even if your handlers don't use anything asynchronous, SelectNoWait and FireEventAsync likely do.