I am studying a code and i want to understand why using this:
initTime = time()
sleep(1 - (time() - initTime))
instead of:
sleep(1)
The purpose is just to count down the time out until 30, so...
Is not the same thing?
from time import time, sleep
def __wait_for_element__(self, element_tag, locator, timeout=30):
"""Wait till element present. Max 30 seconds"""
result = False
self.driver.implicitly_wait(0)
locator = locator.upper()
for i in range(timeout):
initTime = time()
try:
if locator == 'ID' and self.is_element_present(By.ID, element_tag):
result = True
break
elif locator == 'NAME' and self.is_element_present(By.NAME, element_tag):
result = True
break
elif locator == 'XPATH' and self.is_element_present(By.XPATH, element_tag):
result = True
break
elif locator == 'CSS' and self.is_element_present(By.CSS_SELECTORS, element_tag):
result = True
break
else:
logging.info(f"Error: Incorrect locator = {locator}")
except Exception as e:
logging.error(e)
print(f"Exception when __wait_for_element__ : {e}")
sleep(1 - (time() - initTime))
else:
print(
f"Timed out. Element not found with {locator} : {element_tag}")
self.driver.implicitly_wait(DEFAULT_IMPLICIT_WAIT)
return result
CodePudding user response:
time() - initTime
is the time of reading each repetition of the loop.
For a single repetition of the loop, it takes time() - initTime for reading 1 - (time() - initTime) of sleep.
At total: 1 - (time() - initTime) (time() - initTime) = 1 second.
Therefore, when using sleep(1 - (time() - initTime))
, each loop repetition time is very close to 1 second.
Why not using sleep(1)
? -Because it is not as precised. Each loop iteration will last for more than 1 second: (time() - initTime) of reading it 1 second of sleep.