Repeatedly invoking the debounce function

When invoking the searchkeyword function on keyUp, my goal is to prevent or clear the timeout of $emit when a new letter is quickly typed. This way, I only want $emit to be called a few times. However, currently, the console triggers debounce on every searchkeyword call.

  methods: {
    searchKeyword : function() {
      var scope = this;
      (this.debounce(function(){
        scope.$emit("search-keyword", scope.keyword);
        console.log("Called");
      },350))();
    },
    debounce: function (func, delay) {
        var timeout;
        return function() {
          const context = this;
          const args = arguments;
          clearTimeout(timeout);
          timeout = setTimeout(() => func.apply(context, args), delay);
        }
      }
    }

Answer №1

Great approach! Setting a timeout and then clearing it is a widely recognized method for debouncing. You can find a detailed explanation of this technique in this response.

One issue to address is that you are creating a new debounced function every time you call searchKeyword, and immediately executing it.

The correct way to handle this is by directly passing the debounced function instead.

const debounce = (fn, delay) => {
  let timeout;

  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(_ => fn.apply(context, args), delay);
  };
};

new Vue({
  el: '#root',
  name: "App",
  data: _ => ({ called: 0 }),
  methods: {
    doSomething: debounce(function() {
      this.called += 1;
    }, 2000)
  },
  template: `
    <div>
      <button v-on:click='doSomething'>Do Something</button>
      I've been called {{ called }} times
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='root'></div>

It's also worth noting that debounce does not necessarily have to be a method within your component.

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

Error Message: "Duplicate variable declaration detected"

This piece of code is causing me some major headaches. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="#" data-source="ryedai">Ryedai</a> <a href=&q ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

Encountered an error while trying to access an undefined property during an Angular Karma

I'm currently working on testing a service function that involves multiple $http.get() calls. The function being tested returns a promise but the test is failing with an error stating response is undefined. Below is the test script: it('should ...

Do you know the method to make a Youtube iframe go fullscreen?

I am encountering an issue with developing an iframe where I am unable to make it go fullscreen from within the iframe. Fullscreen API works when both the iframe and hosting website are on the same domain, as well as triggering fullscreen from outside the ...

Utilizing Electron API within an Angular Component

I'm hoping to utilize a locally stored video file in electron and play it within my angular component. Despite exposing the loadLocalFile function to prevent the need for setting nodeIntegration to true, I keep receiving a Security Warning : This re ...

Ways to showcase the outcome of a spin after each rotation

I am currently working on a spinning code snippet that allows users to spin and potentially win different amounts. The code includes functionality to prevent more than 3 spins, set random rotation values, and animate the spinning effect. However, I now wa ...

What is the reason behind $(this).text() returning an empty string when clicking on an li element?

Can anyone explain why clicking on this element returns a blank string ""? function saveSelection() { var selectedValue = $(this).text(); // The value here is "" } This pertains to: <ul> <li data-bind="item" onclick="saveSelection();"> ...

Duplicate the image from a specific div to another div, ensuring that only one clone is created

I'm trying to replicate an image in multiple spots within a frame, but I can only manage to get one instead of many. Can someone please tell me what I'm doing wrong? I am creating a map of terrain where I need to clone images from one div to anot ...

Scroll to the bottom with jQuery Chat feature

Is there a way to check if a user is at the bottom of a messages div when new messages are added? Currently, my script automatically scrolls to the bottom when the chat is loaded or a new message is sent. However, I don't want it to scroll to the bott ...

What is the best way to trigger a function exclusively upon clicking a particular element?

My goal is to enable the user to interact with the model by positioning cubes in space upon clicking the "Cubes Mode" button. I currently have a script from the three.js website that achieves this, but I want it to only run when the mentioned button is cli ...

Experience seamless navigation with Highstock's fluid panning feature

I'm attempting to achieve seamless panning on a basic highstock chart by clicking and dragging within the plot area. Interestingly, I have found that this works flawlessly when my data is not based on timestamps: data: [-25.1,-23.8,-19.9,-19.1,-19.1 ...

Is there a way to specify object keys in alignment with a specific pattern that allows for a variety of different combinations

I am seeking a way to restrict an object to only contain keys that adhere to a specific pattern. The pattern I require is: "{integer}a+{integer}c". An example of how it would be structured is as follows: { "2a+1c": { // ... } } Is there a ...

Check the data from the radio button selection

I am facing an issue with reading the values of radio buttons in a list, all of which have the same id. Despite trying to retrieve the value of each individual radio button, my code only reads the value of the first radio button. <script src="//ajax. ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

What is the process for implementing a Content Security Policy to enable the loading of external JS files from a CDN in ExpressJS?

When working with ExpressJS, the HTML file is loaded in the following manner: app.use(express.static(__dirname + '/src/templates/')); Within the HTML file, here is an example of a meta tag containing Content Security Policy: <meta http-equiv= ...

Having trouble printing a section of a webpage after making CSS adjustments

When trying to print part of a page, I used the following method. It successfully prints that portion of the page, however, it does not preserve the CSS effects. <body> <h1><b><center>This is a test page for printing</center&g ...

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...

What are some best practices for frontend and backend development when dealing with server responses containing a large number of items?

I am interested in best practices for handling server responses with a large list of items. When a client sends a search request to the server, and the server finds thousands of matching items (sorted or not), how should this be managed? For example, if th ...

execute a script using an npm module

Imagine having a function like this index.js greet = () => { console.log('hello'); } greet(); and you want it to execute as soon as the page loads, so you include greet();. This works fine when the file is imported in your index.html in ...

Iterating through each object in the JSON file to showcase details about planes

Question How do I set up a functional example of these airplanes? Background I seem to have the initial part working, indicating that my loop may be causing issues. While I can extract the number of planes, I'm facing difficulties displaying all th ...