Understanding execute async script in Selenium

SeleniumAutomation TestingTesting Tools

We can use the executeAsyncScript method in Selenium webdriver. For an executeAsyncScript method, JavaScript Executor runs an asynchronous part of JavaScript with the reference to the present selected window or frame. In contrast to executeScript, the scripts which run with executeAsyncScript method, should be completed by invoking the given callback.

The callback is always added as the last argument within the executed function. The first argument passed is used to get the script result.If the script consists of a return statement, then the below rules are followed −

  • A webelement is returned for an HTML element.

  • A double is returned for a decimal number.

  • A long is returned for a non-decimal number.

  • A Boolean is returned for a Boolean number.

  • A string is returned for all the other cases.

  • A list of objects is returned following the above rules for an array.

  • If the value is null or there is nothing to return, a null is returned.

We can perform the below tasks with the executeAsyncScript method −

  • To set the browser timeout.

  • To synchronize a test with an AJAX application.

  • To inject an XMLHttpRequest and wait for the result.

The arguments of executeAsyncScript method can be Boolean, string, webelement, list or a number. An exception is raised, if the arguments are not of these types. The arguments shall be available using the arguments keyword.


JavascriptExecutor j = (JavascriptExecutor) driver;
("window.setTimeout(arguments[arguments.length - 1], 800);");


import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ExecuteAsyncScriptMethod{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      //get current system time
      long s = System.currentTimeMillis();
      // Javascript executor
      JavascriptExecutor j = (JavascriptExecutor) driver;
      //executeAsyncScript method to set timeout
      ("window.setTimeout(arguments[arguments.length - 1], 800);");
      "Time Elapsed is: " + (System.currentTimeMillis() - s));


Updated on 01-Feb-2021 12:33:22