Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user.

One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize this, I would prefer to break it into batches and only perform the analysis during periods of user inactivity rather than for every change of the bound variable.

The code snippet for a straightforward analysis could be as follows:

var app = new Vue({
  el: '#root',
  data: {
    message: ''
  },
  computed: {
    // a computed getter
    len: function() {
      // `this` references the vm instance
      return this.message.length
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<div id="root>
  <input v-model="message">Length: <span>{{len}}</span>
</div>

My issue is that the function() gets called every time the message changes. Is there a way to implement throttling or what is a common approach to addressing such problems in JavaScript?

Answer №1

It functions as intended, following the guidelines outlined in the documentation:

Any bindings that rely on computed property will update when the original data changes

There is an alternative approach:

const app = new Vue({
  el: '#app',
  data: {
    text: '',
    textLength:  0
  },
  methods: {
    countLength: _.debounce(
      function() {
        this.textLength = this.text.length;
      }, 
      300 // milliseconds
    )
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.js"></script>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4d383039253330202c21372766596678">[email protected]</a>"></script> <!-- underscore import-->
<div id="app">
  <input v-model="text" v-on:keyup="countLength">Character Count: <span>{{ textLength }}</span>
</div>

For a complete example, visit: https://v2.vuejs.org/v2/guide/computed.html#Watchers

p.s. An insight from the author of `vue` regarding the synchronous nature of `computed`:

p.p.s A comprehensive article discussing the distinction between `debounce` and `throttle`: Informative Read

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 it permissible to use multiple JWT tokens in the HTTP header?

Currently, I have implemented the jwt access and refresh token pattern for client-server communication. The method involves sending two jwt tokens in the header: the access token and the refresh token. This is done by adding the following code to the heade ...

Displaying information on a chartJS by connecting to an API using axios in VueJS

Struggling with inputting data into a ChartJS line-chart instance. The chart only displays one point with the right data but an incorrect label (named 'label'): Check out the plot image The odd thing is, the extracted arrays appear to be accura ...

Using jQuery to perform global search and replace with a variable

In this scenario, I am attempting to substitute every occurrence of the newname variable with a hyphen (-). However, in my specific case, newname is being interpreted as text instead of a variable. var newname = 'test'; var lastname = $(this).a ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

JavaScript forEach functionality is not compatible with Dynamics CRM 2016

I'm currently working on writing some JavaScript code for a ribbon button in Dynamics CRM 2016 that will extract phone numbers from a list of Leads displayed in the Active Leads window. However, I've encountered an error message when attempting ...

What is the best way to transmit JSON data to a Web API?

As I work on developing a website with web API integration, I encountered an issue while trying to send JSON data to my controller. Multiple actions were found that match the request: Post on type AuctionWebsiteASP.Controllers.MovesController readDatab ...

The function insertAdjacentHTML does not seem to be functioning properly when used with a

I am working with a parent element that contains some child elements. I create a DocumentFragment and clone certain nodes, adding them to the fragment. Then, I attempt to insert the fragment into the DOM using the insertAdjacentHTML method. Here is an ex ...

Guide to switching classes with jquery

On my webpage, I have a star rating system that I want to toggle between "fa fa-star" and "fa fa-star checked" classes. I found some information on how to do this here: Javascript/Jquery to change class onclick? However, when I tried to implement it, it di ...

Dynamic binding in AngularJS with ng-repeat allows for seamless updating of data

I recently started using a helpful library called Angular Material File input <div layout layout-wrap flex="100" ng-repeat="val in UploadDocuments"> <div flex="100" flex-gt-sm="45"> <div class="md-default-theme" style="margin-le ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

I am looking for assistance constructing a task management application using vue.js

I am facing an issue with developing a to-do list using Vue.js. The goal is to add tasks to the list by entering them and clicking a button. Once added, the new task should show up under "All Tasks" and "Not finished". Buttons for marking tasks as " ...

The functionality of core-ui-select is not functioning properly following the adjustment of the

I've implemented the jquery plugin "core-ui-select" to enhance the appearance of my form select element. Initially, it was functioning perfectly with this URL: However, after applying htaccess to rewrite the URL, the styling no longer works: I&apos ...

Creating a URL using Form Fields with Javascript or jQuery - Reg

Creating a Custom URL with Form Fields using JavaScript or jQuery I am looking to generate an external link by incorporating a form with a dynamic variable as shown below: (Where 2500 can be customized based on user input) The final URL will be display ...

Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript? If so, can this calculation be done dynamically (such as on window resize)? The g ...

Utilizing vuelidate in Vue 3: Overcoming Decorators Challenge in Composition API (`<script setup>`)

Currently working on upgrading from vue 2 to vue 3 and encountering an error with the @Component decorator: "Decorators are not valid here.ts(1206) (alias) Component(options: Vue.ComponentOptionsBase<Vue, any, any, any, any, any, any, any, string, ...

How to access a custom filter in ng-repeat using AngularJS

I'm working on creating a filter to sort through the items displayed in a table. Specifically, I want to filter out items based on a certain property value that may change depending on user input. I have attempted the following approach and it seems t ...

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

Copying to the clipboard now includes the parent of the targeted element

Edit - More Information: Here is a simplified version of the sandbox: https://codesandbox.io/s/stupefied-leftpad-k6eek Check out the demo here: The issue does not seem to occur in Firefox, but it does in Chrome and other browsers I have a div that disp ...