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
you’re looking for
clearInterval()
or as mentioned, a better solution would be to usesetTimeout
andclearTimeout
insteadAfter it finds the button
Call clearInterval() method to stop your interval.
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)
Try adding:
To your code.
This checks if the element exists in the code and returns true if the element exists:
This stops the loop testData returns true.