From WebDriver documentation:
setScriptTimeout
(long time, java.util.concurrent.TimeUnit unit)
Sets the amount of time to wait for an asynchronous script
to finish execution before throwing an error. This works only
for Assync scripts (executeAsyncScript)
Let's run a simple javascript: (Do not set setScriptTimeout
) - Now this shall execute without throwing any issue.
((JavascriptExecutor) driver).executeScript("alert('hello world');");
Lets run a simple Assync Script: ( Do not set setScriptTimeout
) - This shall fail with error - "Timed out waiting for async script result after 0ms"
((JavascriptExecutor) driver).executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 500);");
To resolve the issue: setScriptTimeout
to 1 Second:
driver.manage().timeouts().setScriptTimeout(1, TimeUnit.SECONDS);
And then run the same Assync Script mentioned above and it shall execute without any error.
Reason:
The default timeout for a script to be executed is 0ms. In most cases, including the examples below, one must set the script timeout WebDriver.Timeouts.setScriptTimeout(long, java.util.concurrent.TimeUnit) beforehand to a value sufficiently large enough
More Reference Links:
When should setScriptTimeout be used?
WebDriver executeAsyncScript vs executeScript
WebDriver Doc