End the setInterval() function when a particular class is displayed

My current challenge involves creating a function that checks for the visibility of the #discountbox element and then clones it to be placed after the .pricebox. However, I am encountering an issue where the cloning process continues indefinitely.

Any suggestions on how to modify the setInterval function so that it stops after finding #discountbox and cloning it once?

Here is a snippet of the HTML:

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

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

And here is the Javascript code:

jQuery(document).ready(addDiscountsummary);

function addDiscountsummary () {
if($('#discountbox').is(':visible')){  
      $("#discountbox").clone().insertAfter("#modal span.price-box");   
    } else {
      setInterval(addDiscountsummary, 1000);
    }
}

Answer №1

If you need to stop a recurring function, consider using the clearInterval() method or for a more efficient approach, utilize setTimeout and clearTimeout instead.

jQuery(document).ready(addDiscountsummary);

function addDiscountsummary () {
   if($('#discountbox').is(':visible')){  //check if the discount box is visible on the page
      $("#discountbox").clone().insertAfter("#modal span.price-box");
      clearTimeout(window.nextTimeout);
   } else {
      window.nextTimeout = setTimeout(addDiscountsummary, 1000); //run every 1000 ms
   }
}

Answer №2

Once the button is located, Use the clearInterval() function to halt the interval.

Answer №3

Consider including the following snippet in your code:

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

This piece of code verifies if a specific element is present within the code and will return true if the element exists:

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

By implementing this, the loop will cease when elementExists evaluates to true.

if(elementExists){clearInterval(addDiscountsummary)}

Answer №4

To stop a recurring action, use clearInterval(intervalID). Ensure that the ID (referred to as interval) is created outside of any function so it can be accessed throughout the page. Call clearInterval(interval) when you have found the desired item.

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)
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to securely store my JWT Token within my application's state?

userAction.js -> Frontend, Action export const login = (userID, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST }); const url = "http://localhost:8080/authenticate/"; const ...

Creating dynamic VueFire references is a powerful feature that allows for more flexibility and customization

I am currently exploring the creation of refs dynamically: The initial ref I created works fine as it is hardcoded, but the second one does not seem to work because it is dynamic: firebase: function(){ return { categories: db.ref('categ ...

Updating the checklist status using an ajax request: A step-by-step guide

Is it better to update the checklist status by making individual ajax calls for each checklist item or by making one call and updating it once completed? I have included a template showing how it currently looks and what I am aiming for. Unfortunately, I ...

Displaying an array of data using ng-repeat, only showing records where the value is found within a field of another object

Within my project, I am working with two types of objects: 'ing' containing fields 'id' and 'field', and 'fObj' containing a field named 'contain'. Using ng-repeat, I am trying to display only those ' ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

A guide to efficiently managing updates and inserts with bulkCreate in node.js

Currently, I am utilizing node.js to facilitate the uploading of an excel file into a database. Furthermore, in my service, I am employing bulkCreate to efficiently upload the data into the mysql db. In order to provide more context, I will outline the str ...

The variables in Next.js reset every time I navigate to a new page

Looking for a way to share a variable between pages in my Next.Js application, I have the following setup in my _app.js file: import { useState } from 'react'; const CustomApp = ({ Component, pageProps }) => { // Variables const [testVa ...

"Incorporate React Redux to dynamically load an endless stream of items in batches of x at a time

In order to efficiently display search results using React - Redux, I want to limit the number of displayed results while maintaining optimal performance. Here is my current approach for getting and displaying the results: handleSubmit(event) { event ...

Title of button to toggle visibility using jQuery

How can I utilize jquery code to extract the text from a td? Here is my current setup: <div id="divName"> <table id="tableName"> <tr> <td id="g${req.Name}</">${req.Name}</td> <td><input type="button" id= ...

Unlock the full potential of the PanelSnap plugin in your angular2 project with these easy steps

I had been successfully using the jquery.Panelsnap plugin on my static HTML pages. However, as I am now transitioning my application to angular8, I am encountering difficulties in referencing the PanelSnap plugin. npm install panelsnap Within my app. ...

Displaying NodeJS error messages directly in the main HTML file

After creating a form using NodeJs and implementing input validations that display errors when users enter incorrect values, I encountered an issue where the errors appear on a new blank page instead of within the main HTML file itself with stylish formatt ...

Using JavaScript to open a document file in Chrome at launch

Is it possible to automatically open a doc file stored on my C:// drive when a link is clicked on my HTML page? Here is the code I have been using: <a href="C://mytestfile.doc">Click Me To launch the DOC FILE</a> Unfortunately, instead of op ...

How come the date is not showing up inside the <p> tag?

Check out this snippet of HTML code: <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="bootstrap_4.5.0&bsol ...

Ways to extract the maximum value from a dataset formatted in JSON

My current project involves using highcharts to create data series for plotting the chart, which looks something like this: series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] I have been considering ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

Guide to creating a synchronous wrapper for jQuery ajax methods

I've made the decision to switch from synchronous ajax calls to asynchronous ones due to lack of support in most modern browsers. My code is currently reliant on synchronous (and dynamic) ajax calls to client-side functions that must be completed befo ...

validating if Object may be either 'null' or 'undefined'

In the code snippet below, I am attempting to verify whether hostel.country.address is null: return hostel.country.address && hostel.country.address.internalEmployeeIdentifier !== null || hostel.country.address.exter ...

Verifying if a JavaScript textarea is empty

How can I make a textarea have a visible border around it when the string is empty, without needing to first input and delete text? Here is my current code: $("#message-box").on("keyup", function(){ var charCount = $("#message-box").val().length; ...

"Revamp your site with Vue and API for dynamic background

I'm faced with an issue where I am attempting to modify the background of a joke fetched from an API, but for some reason, the background is not changing and I can't seem to identify why. The main problem lies in my inability to change the proper ...

In Javascript, you can throw, instantiate a new Error(), and populate its custom properties all in a single line of code

Can all of this be done in a single line? if (!user) { const error = new Error('Invalid user.') error.data = someObject error.code = 401 throw error } Here's an example (with data and code properties populated) if (!user) th ...