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

What is the correct way to customize colors for specific components in Material-ui?

Struggling with theming in Material-UI, particularly when it comes to customizing element colors. Some elements default to 'theme.palette.main.dark' and I want to override this behavior. For example, the TextField and SpeedDial components automa ...

I have decided to integrate Laravel with Vite for building CSS and JS. However, when I attempted to run `npm run dev`, it appeared to execute but was accompanied by an error in the background that

Hi there, I'm new to Laravel and I've created a small app that primarily uses CSS and JS scripts. Everything was working fine in my development environment, so I decided to push it to a production server. However, after installation, my code does ...

Tips for retrieving the text enclosed within a <span> tag using jQuery

I am new to jQuery and came across this code online for a questionnaire. I want to save the selected options but I am not sure how to do it. " $.fn.jRadio = function (settings)" What is the purpose of this setting? " var options = $.extend(_de ...

The jQuery load() callback triggering a POST request unexpectedly instead of a GET request

Utilizing jQuery's load() method, I am attempting to insert a page fragment into a new page. It appears that this can only be achieved with load(), as get() does not support page fragments. Upon completion of the load, it is necessary for me to invok ...

How can we wrap the Vuex store within a Vue plugin's install function?

I developed a plugin that utilizes Vuex for state management. // plugin.js import Vuex from "vuex"; import store from "./store.js"; export default { install(Vue, options) { const storeInstance = new Vuex.Store(store); Vue.pr ...

Issues with dynamically adding or removing scroll in jQuery are not being resolved

I am trying to implement a dynamic scrolling feature in my post scenario. The goal is to automatically add a vertical scroll when the number of dynamic inputs reaches a certain threshold. Specifically, if there are more than 5 dynamic inputs created, a ver ...

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

Pagination Component for React Material-UI Table

I am interested in learning about Table Pagination in React UI Material. Currently, my goal is to retrieve and display data from an API in a Material UI Table. While I have successfully implemented some data from the API into the Material UI Table, I am ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

How can JavaScript nested AJAX requests and promises be properly chained together?

I'm currently facing a dilemma when it comes to setting the correct order of execution for the tasks at hand. Let's say I need to initiate an AJAX call, then handle the data and store it in IndexedDB using the idb-keyval library, which operates o ...

AngularJS Constants in TypeScript using CommonJS modules

Let's talk about a scenario where I need to select a filter object to build. The filters are stored in an array: app.constant("filters", () => <IFilterList>[ (value, label) => <IFilterObject>{ value: value, label: label } ]); i ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Display a list with a set limit and an option to show more by clicking

I am currently struggling to develop a list of items that displays 3 items per row, and when the "show more" button is clicked, another 3 items should be displayed. My issue arises when using map and slice, as this method results in rendering 3 of the same ...

AngularJs setPristine() not resetting the invalid status of a form

Is there anyone who can assist with the provided Plunker code? All you need to do is submit the form with just one required field filled out. This action will result in validation errors being displayed. When you reset the form by calling both setPristine ...

Why do browsers fail to cache Java scripts (Ajax) properly?

After creating a cascade drop-down list box with JQuery, the user can choose a state from the first drop-down and then the second drop-down will be filled with the relevant cities based on the selected state. However, I am facing an issue with caching in ...

Trouble with attaching a click event to a jQuery datepicker

I am attempting to attach a click event to .ui-state-default after a jQuery datepicker has been displayed (I do not have access to the html generating the datepicker so I cannot utilize any datepicker-specific events) and it functions properly using $.bind ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...