How can I properly reset a timeout duration?

I'm currently working with a function that looks like this:

function blabla(){
    ...

    setTimeout(() => {
        //do some stuff
    }, 10000) 
}   

My question is, how can I reset the time of the timeout (10000) if the function was called and the timeout was not finished yet?
I attempted to cancel the timeout if it exists, like so:

function blabla(){
    ...

    if(to){
       clearTimeout(to)
    } 

    let to = setTimeout(() => {
        //do some stuff
    }, 10000) 
}  

However, I encountered an error indicating that to is undefined. What is the correct way to determine if a timeout exists or not? Is there a more efficient approach to achieve this task?

Answer №1

Make sure to declare to before the if statement, ensuring that it is defined when the condition is checked. You can leave its value undefined initially and assign a value later on.

It's advisable to declare to outside the function to maintain its state between function calls.

Take a look at this demo to see how the clearTimeout function works in action. Even after calling the blablah() function twice, you'll only see "hello" once because the second call cancels the original timeout.

var to;

function blabla() {
  //...

  if (to) {
    clearTimeout(to)
  }

  to = setTimeout(() => {
    //do some stuff
    console.log("hello");
  }, 10000)
}

blabla();
blabla();

Answer №2

Avoid using let since its scope is limited to the function block. Instead, use var so that the variable is accessible across multiple function calls.

Answer №3

Avoid using global variables for this purpose as they are not reusable. It's best to create a wrapper function instead, as this is a common programming pattern. You can either implement this natively or use an npm package.

Many JavaScript libraries come with built-in debounce functions. The main goal of these functions is to minimize unnecessary calls by preventing a function from being executed multiple times in quick succession. Regardless of the library used, all debounce functions rely on JavaScript's native setTimeout function.

Check out https://www.npmjs.com/package/debounce for more information:

function debounce(func, wait, immediate) {
    let timeout;
    return function() {
        let context = this,
            args = arguments;
        let later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        let callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

var example = debounce(function(){
     console.log(5)
}, 5000);
example()
example()

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

Methods for Addressing Absent SocketIO Session Data Within an Express Route Handler

My goal is to establish communication between Express and SocketIO on a nodejs server, allowing them to share session data. After conducting thorough research online, I discovered a potential solution at https://socket.io/docs/v3/faq/#Usage-with-express-se ...

Extracting the id of an element using jQuery

The desired outcome is for the code to print the id of the selected div, but it's not working as expected. I've reviewed it multiple times but couldn't pinpoint the error. Any assistance would be greatly appreciated. Here is the HTML: < ...

In the Firebug console, Ajax posts are highlighted in a vibrant red color

Upon executing the code provided, the Firebug was enabled. While submitting the form, in the console, the message "post to login_submit.php" appeared in red. However, there was no response received as well. <!DOCTYPE html> <html> ...

Using Three.js to create a blurred SVG texture from a canvas

I am attempting to apply an SVG as a texture over a model with UV mapping, but it appears very blurry. I'm using the texture from a 2D canvas, which looks fine on its own, but once applied to the model, it doesn't look good at all. Any suggestion ...

Incorporating an HTML/Javascript game into a reactJS website: A step-by-step

After developing a game using plain javascript and HTML along with a few JS libraries, I find myself inquiring about the process of integrating this game into my ReactJS website. Typically, the game is initiated by opening the index.html file located with ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

Obtain the specific key's value from a new Map state

In my code, I've defined a variable called checkedItems as a new Map(); When I try to console.log(checkedItem), the output is as follows: Map(3) {"1" => true, "1.5" => true, "2" => false} Is there a way ...

When the "errors" property is not utilized, the error "Cannot read property '_transitionClasses' of undefined" is encountered in vue.runtime.common.js

I encountered a strange issue while running a test on a component that utilizes vee-validate. What's even more bizarre is that the error doesn't occur when I use this.errors in the component (even simply including console.log(this.errors) seems t ...

The side menu in Bootstrap dropdown experiences a one-time functionality

When navigating through a responsive top menu with Bootstrap, everything works seamlessly - from toggling the menu to dropdown functionality. However, I encountered an issue with the side menu as nav-pills used to select tab-panes. <div class="containe ...

Refine objects based on their properties without removing them from the dataset

I have a specific object structured as follows: var myObj: { 2:"None", 20:"A", 31:"A", 32:"A", Social:"B", Method:"None" } My goal is to retrieve the object without the properties 'Social' and 'Method'. Initia ...

What is the best way to route a localpath to a different page including parameters in Nuxt Js?

Hello, I am facing an issue where I need to pass parameters in the URL to another page in NuxtJs props: { idPending: { type: Number, required: true } }, methods: { fetchpage() { const orderId = this.idPending; this.$rou ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

Utilizing Regular Expressions to Substitute 'null' in API Data with a Custom String in JavaScript

I'm working with an API to gather information about books, including the title and author. However, I've noticed that some authors' data is returned as 'undefined'. I had the idea of using regular expressions (RegExp) to replace th ...

Is my approach to CSV parsing correct if I am receiving the error "Unable to assign property 'processing' to undefined"?

In our database, we store words along with their categories. I have a new requirement to enable the word administrator to upload multiple words at once using a CSV file. Currently, our system only allows for single-word additions at a time. My solution was ...

Is it possible to fulfill a promise within an if statement?

I'm fairly new to using promises in JavaScript, and I am currently facing an issue where a function needs to execute before running some additional code in another function. The problem arises when the promised function includes an if statement that l ...

I am looking for a way to generate unique dynamic IDs for each input textbox created within a PHP while loop. Can

How can I retrieve the ID of a selected text box generated within a while loop in order to update a field similar to phpMyAdmin? <?php while($row=mysql_fetch_assoc($result)) { ?> <tr> <td><input type ...

Constructing a JSON schema for a dynamic aggregate query

Looking to create a query that matches fields with data in them. Here is an attempt: var matchStr = {}; if (received.user) { matchStr = { "_id": { "$regex": received.user, "$options": "i" } }; } if (received.name) { matchStr += { "name": { " ...

Tips for defining header and parameters when using route.get in Node.js

Looking to add custom headers and parameters when using route.get in Node.js? I am trying to set a specific value for the header and pass parameter values in the API URL. router.get("/getdata", async (req, res) => { // Set custom header re ...

implementing ajax form submission in codeigniter

After submitting my form, validation is checked in the JavaScript file, and then the kickerLogin() function is called. I receive an alert message of datastring. However, the data is not sent to the specified URL in the AJAX request, but the form still ge ...

What is the best way to remove all attributes from one interface when comparing to another?

Consider the following two interfaces: interface A { a: number; b: string; } interface B { b: string; } I am interested in creating a new type that includes all the keys from interface A, but excludes any keys that are also present in interface B. ...