Home > Blockchain >  How to stop looking for an element after a certain period using JavaScriptExecutor on an unlimited s
How to stop looking for an element after a certain period using JavaScriptExecutor on an unlimited s

Time:06-08

Suppose I want to look for my post on a facebook page by scrolling down. And I am looking my post based on my profile name. I use Javascriptexecutor to start scrolling down until it finds the post but what if it won't get my post on the page then how can I stop the executor after certain period of time as facebook page keeps updating and loading in seconds as we go down and down. It will go in continuous loop. Any suggestions would help.

Example -

WebElement element = driver.findByElement(By.name("Myname")); JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("arguments[0].scrollIntoView();", element);

CodePudding user response:

This will execute any code inside the while loop for a pre-defined amount of time. In this example I have it set to print out an incrementing variable for 5 seconds.

int i = 0;
    
    long start = System.currentTimeMillis();
    long end = start   5 * 1000;
    while (System.currentTimeMillis() < end) {
        System.out.println(i);
        i  ;
    }

So for you it'd be -

    long start = System.currentTimeMillis();
    long end = start   desiredTimeDuration(inSeconds) * 1000;
    while (System.currentTimeMillis() < end) {
        whatYouWantItToDoForSetAmountOfTime
    }

Hope this helps, cheers!

  • Related