Make sure to clear the timeout in JavaScript before re-calling the function again

Scenario:

Whenever a user clicks on a cell within the "#test" table, the "update_func" function will run and repeat every 10 seconds.

If the user clicks on the same cell or another cell, multiple instances of "update_func" start running simultaneously every 10 seconds.

Inquiry:

To prevent multiple instances of "update_func" from running at the same time, where should I implement the clearTimeout() function in the code?

The existing script is as follows:

$("#test").on("click", td, function() {
        //do something..
        update_func(v1,v2,v3);
});

function update_func(v1,v2,v3){
    $.ajax({
        url:"update.php",
        method:"POST",
        data:{testvalue:v1},
        success:function(data){
            $('#testbox').html(data);
        }
    }).always(function () {
        window.setTimeout(function() { update_func(v1,v2,v3); }, 10000);
    });
}

Answer №1

To ensure proper handling of timeouts, it is recommended to store the timeout ID in a variable within the outer scope. This way, you can easily clear the timeout when needed:

let timeoutId;
$("#test").on("click", td, function() {
        // Perform some actions..
        clearTimeout(timeoutId);
        update_func(v1,v2,v3);
});

function update_func(v1,v2,v3){
    $.ajax({
        url:"update.php",
        method:"POST",
        data:{testvalue:v1},
        success:function(data){
            $('#testbox').html(data);
        }
    }).always(function () {
        timeoutId = window.setTimeout(function() { update_func(v1,v2,v3); }, 10000);
    });
}

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

Challenges with moving images in Unslider

There seems to be an issue with the unslider-arrows on the unslider banner. The images are not sliding properly when transitioning to the next image without user input. Instead, they resize from small to full size starting at the top of the .banner div. ...

The scrollOverflow feature in fullPage.js is not properly detecting the height of dynamically generated content

I have successfully implemented fullpage.js on my website. Everything is working perfectly with fullpage.js, but I am facing an issue when trying to open a div on click of pagination. Specifically, the browser scroll gets disabled when the div containing a ...

Tips for enabling animation for AmCharts animateData feature

To achieve a real-time values per minute chart, the last bar value is to be incremented every minute after its addition. Additionally, a new bar with a value of 1 will be added each minute while removing the oldest bar. All these changes need to be animat ...

To prevent the need for redundant iterations, arrange an object based on a specific field

Looking for a way to avoid repeating the same loop multiple times while sorting an object efficiently. Take a look at this sample object: movies = [ { title: "The Lord of the Rings: The Fellowship of the Ring" year: 2001 ...

Troubleshooting: ajax functionality experiencing issues despite implementation of async and await keywords

Below is the code that is currently functioning well. $.ajax({ url: '?module=abc&action=xyz', //Ajax events beforeSend: function (e) { // }, success: function (e) { const URL1 = '?module=mno&action=pqr&apo ...

What is the best way to add an element after a specific child element with jquery?

Is there a way to add a paragraph element after a specific div class element? I am looking to include a p element within the second text div class. I attempted a solution, but it is not producing the desired result. The current solution is not effective. ...

Learn how to retrieve data by clicking on the previous and next buttons in FullCalendar using Vue.js

Seeking guidance on retrieving calendar data from the database for my Vue frontend, I have incorporated the fullcalendar API. Successfully able to retrieve data for the current week, however facing challenges when attempting to fetch data for the previous ...

Send the contents of a `<ul>` element to the server using AJAX for form submission

Can someone assist me in submitting a serialized <ul> list through an AJAX post form request? I need help with this process. Below is my current code snippet. HTML: <form id="update_fruit_form" method="post" action="/update_fruits" accept-charse ...

Is it possible to create a button that can bring in a .css file?

Is there a way to create a button that imports styles from a .css file, or is it possible to change multiple CSS properties with buttons to create different website themes? This is the CSS file I have: .body { background-image: url("example.png"); } ...

Implementing Firestore Read Limitations in a React Application

I have encountered an issue with Firebase billing based on the number of document reads. There is a daily limit of 50k reads per day in Firestore, but when I try to fetch documents in my React app, it triggers a quota exceeded error. FirebaseError: Request ...

Access-Control-Allow-Origin causing a one-of-a-kind session problem

When trying to access data using cross-domain requests from multiple domains, I have included the following code in a PHP file at the backend: header("Access-Control-Allow-Origin: *"); Each time a new session is created for every request, resulting in a ...

Customize default progress bar in browsers

One feature of my website allows users to update their personal information, profile image, background image, and more. After clicking the submit button, a loading screen appears with a progress percentage displayed at the bottom left corner of the page (i ...

Refusing to include two values due to the presence of a comma in JavaScript

I'm trying to add two values with commas and .00 (Example: 1,200.23 + 2,500.44) but it's not working because the textbox includes commas as required by my system. The result shows NaN because the comma is considered a special character. It was w ...

sending a string to opencart through ajax

I'm currently facing an issue with my Opencart website. I'm attempting to utilize ajax on the frontend to send data to a php controller on the backend, but I'm having trouble extracting the value from the request in the backend. Here is the ...

Is there a way to adjust the size of the canvas element in HTML without compromising quality or resorting to zooming?

I'm currently working on a basic modeling application for the web. The main component of my app is a canvas element that I'm trying to size correctly. However, when I set the height and width using CSS, it scales the entire canvas and compromises ...

Create an array populated with unclosed HTML tags that need to be rendered

I'm trying to display a simple list, but it seems like React is having trouble rendering unclosed HTML elements that are pushed onto the list. This results in an error: ReferenceError: el is not defined If I use single quotes (') bookingStat ...

Issue accessing object property in Handlebars template with ExpressJs

Personalized Routes: router.use(function(req, res, next) { res.locals.currentUser = req.user; next(); }); /* Accessing the home page. */ router.get('/', function(req, res, next) { console.log(res.locals.currentUser.username); ==>> t ...

Sending a JavaScript variable to PHP in order to specify the timezone

I'm working on setting the timezone for every user in the navbar.php file that's included on all pages of my website. After finding a helpful js script, I am able to echo the variable 'Europe/Brussels' to identify my timezone correctly. ...

Efforts to toggle visibility of icons in React

One issue I encountered is with the Navbar in mobile mode, where the icons are covering the menu. Refer to the image for a visual representation of the problem. https://i.sstatic.net/7eNeg.png To address this issue, my plan is to hide the icons when the ...

JSONP callback function enables cross-domain communication by allowing a

After delving into the world of JSONP callback functions, I decided to familiarize myself with the concept by researching articles. To further understand JSONP, I uploaded a JSON file onto the server - json file Below is the JavaScript code I used to fet ...