# Timeout Decorator

# Implement a timeout decorator that limits a function's execution time by interrupting it if it exceeds a specified time limit.
# Requirements:
#     Implement a timeout decorator that accepts a single argument, seconds, which specifies the maximum allowed execution time for the decorated function.
#     If the decorated function exceeds the specified seconds, raise a TimeoutError with an appropriate error message.
#     The decorated function should return its result normally if it completes within the allowed time.
#     The decorator should work with both synchronous and asynchronous functions.

import random
import time
import asyncio


@timeout(5)
def some_unpredictable_func_sync():
    time_to_sleep = random.randint(1, 10)
    time.sleep(time_to_sleep)
    return time_to_sleep


@timeout(6)
async def some_unpredictable_func_async():
    time_to_sleep = random.randint(1, 10)
    time.sleep(time_to_sleep)
    return time_to_sleep


while True:
  print(some_unpredictable_func_sync())


async def runner():
    while True:
      print(awaut some_unpredictable_func_async())


asyncio.run(runner())


# Output example:
# 2  # or any number between 1 and 5
# 1  # or any number between 1 and 5
# TimeoutError: `some_unpredictable_func` execution time exceeded 5 seconds

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: