Script Timeout

Introduction

In Selenium, some JavaScript operations may take longer than expected to complete. If Selenium waits indefinitely for these scripts, your automation tests can become unresponsive.

Script Timeout allows you to specify the maximum amount of time Selenium should wait for an asynchronous JavaScript script to finish executing. If the script does not complete within the specified time, Selenium throws a TimeoutException.

In this tutorial, you’ll learn what Script Timeout is, why it is used, its syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is Script Timeout?

Script Timeout is a Selenium feature that defines the maximum time Selenium should wait for an asynchronous JavaScript to complete execution.

It is mainly used with:

  • execute_async_script()

If the script completes within the timeout, Selenium continues execution.

If the timeout expires first, Selenium throws a TimeoutException.


Why Use Script Timeout?

Script Timeout helps you:

  • Prevent JavaScript execution from hanging indefinitely.

  • Handle long-running asynchronous scripts.

  • Improve automation reliability.

  • Detect JavaScript performance issues.

  • Prevent test execution from getting stuck.


Syntax

driver.set_script_timeout(20)

Where:

  • driver → WebDriver instance.

  • 20 → Maximum script execution time in seconds.


Example

The following example sets a Script Timeout of 10 seconds and executes an asynchronous JavaScript function that waits for one second before returning the value "done" using a callback function.

from selenium import webdriver


# Topic: 24. Advanced Synchronization - Script Timeout
# Practice site: https://the-internet.herokuapp.com/
# Run: pytest -s 24_examples/test_03_script_timeout.py
#
# set_script_timeout() sets the maximum time for asynchronous script execution
# to complete.


def test_script_timeout():
    driver = webdriver.Chrome()
    driver.set_script_timeout(10)

    try:
        driver.get("https://the-internet.herokuapp.com/")

        result = driver.execute_async_script(
            """
            const callback = arguments[arguments.length - 1];
            setTimeout(() => callback('done'), 1000);
            """
        )

        assert result == "done"

    finally:
        driver.quit()

Output

Since the asynchronous JavaScript completes in one second, Selenium successfully receives the callback value and continues execution.

done

The asynchronous JavaScript
completed successfully within
the configured timeout period.

If the script takes longer than the configured timeout, Selenium throws a TimeoutException.


Understanding the Code

Create the WebDriver

driver = webdriver.Chrome()

Launches the Chrome browser.


Configure the Script Timeout

driver.set_script_timeout(10)

Sets the maximum amount of time Selenium should wait for an asynchronous JavaScript to complete execution.

In this example:

  • Selenium waits for a maximum of 10 seconds.

  • If the script finishes earlier, Selenium immediately continues execution.

  • If the timeout expires first, Selenium throws a TimeoutException.


Open the Practice Website

driver.get(
    "https://the-internet.herokuapp.com/"
)

Opens Selenium’s The Internet practice website before executing the asynchronous JavaScript.


Execute the Asynchronous JavaScript

result = driver.execute_async_script(
    """
    const callback = arguments[
        arguments.length - 1
    ];

    setTimeout(
        () => callback("done"),
        1000
    );
    """
)

The execute_async_script() method executes asynchronous JavaScript inside the browser.

Unlike execute_script(), Selenium waits until the JavaScript explicitly informs it that execution has completed.


Understand the Callback Function

const callback = arguments[
    arguments.length - 1
];

Selenium automatically passes a callback function as the last argument to every asynchronous JavaScript execution.

The callback function tells Selenium:

  • The script has finished executing.

  • Selenium may continue with the next step.

Without calling the callback function, Selenium continues waiting until the configured timeout expires.


Delay the Execution

setTimeout(
    () => callback("done"),
    1000
);

This JavaScript performs the following steps:

  • Waits for 1000 milliseconds (1 second).

  • Calls the callback function.

  • Returns the value "done" to Selenium.

Since the configured timeout is 10 seconds, the script completes successfully within the allowed time.


Validate the Result

assert result == "done"

Verifies that:

  • The asynchronous JavaScript executed successfully.

  • Selenium received the callback value correctly.

  • The script completed within the configured timeout period.


How Script Timeout Works

The following diagram illustrates the execution flow.

         Execute Async Script
                   │
                   ▼
          Configure Script Timeout
                   │
                   ▼
            JavaScript Starts
                   │
                   ▼
             Callback Invoked?
                │         │
               Yes        No
                │          │
                ▼          ▼
           Continue    Keep Waiting
                            │
                    Timeout Reached?
                       │         │
                      No        Yes
                       │          │
                       ▼          ▼
                Continue Waiting
                            Throw
                     TimeoutException

Practical Example

Suppose an e-commerce website uses asynchronous JavaScript to retrieve product recommendations from an API.

Instead of waiting indefinitely, Selenium waits only for the configured Script Timeout period.

If the JavaScript successfully completes:

  • Selenium continues execution immediately.

Otherwise:

  • Selenium reports a timeout failure.


Automation Testing Example

Consider an online banking application.

After clicking Generate Statement:

  • JavaScript processes the request.

  • Transaction data is retrieved.

  • The report is generated asynchronously.

  • The generated file becomes available for download.

Using Script Timeout ensures Selenium waits only for the allowed duration before reporting a failure if the JavaScript does not complete successfully.


Real-World Example

Script Timeout is commonly used in:

  • Banking applications

  • E-commerce websites

  • CRM systems

  • Healthcare portals

  • Enterprise web applications

  • Applications using asynchronous JavaScript

It is especially useful when automation interacts with custom JavaScript functionality.


Advantages of Script Timeout

  • Prevents indefinite JavaScript execution.

  • Improves automation reliability.

  • Detects slow-running scripts.

  • Saves execution time.

  • Useful for testing asynchronous JavaScript.


Limitations

  • Applies only to asynchronous JavaScript executed using execute_async_script().

  • Does not affect page loading.

  • Does not wait for web elements.

  • Cannot replace Explicit Wait for dynamic elements.


Common Mistakes Beginners Make

Confusing Script Timeout with Page Load Timeout

Many beginners assume both are identical.

They serve different purposes:

  • Page Load Timeout → Waits for an entire webpage to load.

  • Script Timeout → Waits for asynchronous JavaScript execution.


Forgetting the Callback Function

When using:

driver.execute_async_script()

the JavaScript must call the callback function.

Otherwise, Selenium continues waiting until the timeout expires.

Always ensure the callback function is executed when the asynchronous operation completes.


Using Script Timeout for Element Synchronization

Script Timeout does not wait for:

  • Buttons

  • Textboxes

  • Alerts

  • Frames

  • Dynamic web elements

Use Explicit Wait for those synchronization scenarios.


Best Practices

  • Use Script Timeout only with execute_async_script().

  • Set reasonable timeout values (typically 10–30 seconds).

  • Always ensure the asynchronous script calls the callback function.

  • Use Explicit Wait for element synchronization.

  • Monitor timeout failures to identify slow JavaScript execution.


Conclusion

Script Timeout is a specialized Selenium feature used for handling asynchronous JavaScript execution. It prevents automation scripts from waiting indefinitely by limiting the maximum execution time of asynchronous scripts. Although it is less commonly used than Explicit Wait or Page Load Timeout, it is extremely useful when working with custom JavaScript or advanced web applications.


Frequently Asked Questions (FAQs)

What is Script Timeout in Selenium?

Script Timeout specifies the maximum amount of time Selenium waits for an asynchronous JavaScript to complete.

Which method uses Script Timeout?

Script Timeout is mainly used with:

  • driver.execute_async_script()

What happens if the JavaScript exceeds the timeout?

Selenium throws a TimeoutException.

Does Script Timeout wait for page loading?

No.

Use Page Load Timeout to control webpage loading time.

Is Script Timeout commonly used in Selenium projects?

It is mainly used in advanced automation scenarios involving custom asynchronous JavaScript. For everyday web element synchronization, Explicit Wait is more commonly used.


Key Takeaways

  • Script Timeout controls how long Selenium waits for asynchronous JavaScript execution.

  • It is used with execute_async_script().

  • Selenium throws a TimeoutException if the script exceeds the configured timeout.

  • It does not wait for webpages or web elements.

  • Always use a callback function when executing asynchronous JavaScript.

  • Script Timeout is useful for advanced automation scenarios involving custom JavaScript.