Search code examples
javascriptxpathxpath-2.0

click on xpath using javascript delay after element clicked


i am working on xpath script, i want to work it like that it will keep loking for xpath every 1 second and when element/xpath is found it will click the element and then wait for 5 second then again start 1 second to keep looking,


<script>
/**
 * Specify the element XPath
 */
var xpath = "/html/body/div[1]/a[5]";

/**
 * The following lines do not need to be changed
 */
function getElementByXpath(path) {
  return document.evaluate(
    path,
    document,
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null
  ).singleNodeValue;
}

/**
 * Find an element with the XPath
 */
var element = getElementByXpath(xpath);

/**
 * Exit if the element does not exist
 */
if (!element) {
  throw new Error("Error: cannot find an element with XPath(" + xpath + ")");
}

/**
 * Click the element
 */
element.click();

</script>

i have tried setinterval 1000; but it is keep clicking the element every one second it should wait for 5 second before next, when click is done.


Solution

  • It's best to do this with setTimeout rather than setInterval, otherwise you'll need to deal with stopping timers.

    
    var RETRY_DELAY   = 1000;
    var COOLOFF_DELAY = 5000;
    var timerId;
    
    function pollElement() {
      /**
       * Find an element with the XPath
       */
      var element = getElementByXpath(xpath);
    
      /**
       * If the element doesn't exist, wait RETRY_DELAY then retry 
       */
      if (!element) {
        console.log("Element not found with XPath: " + xpath);
        setTimeout(pollElement, RETRY_DELAY);
      }
    
      /**
       * Click the element
       */
      element.click();
    
      /**
       * Wait for COOLOFF_DELAY before checking again
       */
      timerId = setTimeout(pollElement, COOLOFF_DELAY);
    }
    
    function cancelPolling() {
      if (timerId)
        clearTimeout(timerId);
    }
    
    // Start polling
    pollElement();
    
    // Stop polling
    cancelPolling();
    

    EDITED to address additional request made in comment