skip to Main Content

Currently what I’m trying to do is have a function that looks for if the #discountbox element is visible then clone that #discountbox element and place it after .pricebox. Right now what’s happening is that it is placing it after .pricebox and cloning it indefinitely.

How can I get the setInterval to stop after it finds #discountbox and clones it once?

HTML

<div id="discountbox" class="discount-summary">
      You get $5 Off
</div>

<div id="modal">
    <span class="price-box">
      $20.50
    </span>
</div>

Javascript

jQuery(document).ready(addDiscountsummary);

function addDiscountsummary () {
if($('#discountbox').is(':visible')){  //if the container is visible on the page
      $("#discountbox").clone().insertAfter("#modal span.price-box"); //insert add to cart button after view contents buttons     
    } else {
      setInterval(addDiscountsummary, 1000); //check every 1000 ms
    }
}

4

Answers


  1. you’re looking for clearInterval() or as mentioned, a better solution would be to use setTimeout and clearTimeout instead

    jQuery(document).ready(addDiscountsummary);
    
    function addDiscountsummary () {
       if($('#discountbox').is(':visible')){  //if the container is visible on the page
          $("#discountbox").clone().insertAfter("#modal span.price-box");
          clearTimeout(window.nextTimeout);
       } else {
          window.nextTimeout = setTimeout(addDiscountsummary, 1000); //check every 1000 ms
       }
    }
    
    Login or Signup to reply.
  2. After it finds the button
    Call clearInterval() method to stop your interval.

    Login or Signup to reply.
  3. clearInterval(intervalID) will do the trick.
    When your doc loads, set the interval. Make sure the ID (which I am calling interval) is first created outside of any function, available to the rest of the page. When your item is found, clearInterval(interval)

    let interval
    jQuery(document).ready(function() {
      interval = setInterval(addDiscountsummary, 1000);
    });
    
    function addDiscountsummary() {
      if ($('#discountbox').is(':visible')) {
        $("#discountbox").clone().insertAfter("#modal span.price-box");
        clearInterval(interval)
      }
    
    Login or Signup to reply.
  4. Try adding:

    var testData = !!document.getElementById("discountbox");
    if(testData=="true"){clearInterval(addDiscountsummary)}
    else{};
    

    To your code.
    This checks if the element exists in the code and returns true if the element exists:

    var testData = !!document.getElementById("discountbox");
    

    This stops the loop testData returns true.

    if(testData=="true"){clearInterval(addDiscountsummary)}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search