What is SetScriptTimeout-Webdriver
You've got two answers already, neither of which I find explain clearly the point of setting a script timeout.
First, it is important the script timeout affects only JavaScript code executed with executeAsyncScript
and nothing else. In particular, executeScript
is not affected by it.
So why do you want to set a timeout for executeAsyncScript
? Chandan Nayak correctly explained that the default timeout is 0s so you have to change this timeout if you want to use executeAsyncScript
with asynchronous scripts that actually perform some work. But why not just set it to -1
and be done with it? After all, if you set it to -1
then you turn off the timeout. So you won't get any timeouts anymore. Mission accomplished, right? Nope.
What you want to do is set the timeout to a value that allows the code you use with executeAsyncScript
to perform it works while at the same time detect when a script has gone rogue. For instance, if from experience you know that a script you pass to executeAsyncScript
is going to be done in 2 seconds or less (except perhaps in extremely unusual circumstances), then you set the timeout to 2 seconds so that if there is a bug somewhere and the code never terminates, you get a timeout after 2 seconds. Otherwise, Selenium will happily wait forever for the script to complete.
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