Looking for the time trigger feature in jQuery using typeahead search?

Is there a way to trigger an event every 3 seconds in Laravel Vue.js? I am currently using jQuery in my script. The issue is that when I type something in the search input field, the event is triggered after each character I type. What I want is for the event to be triggered only when I stop typing for at least 3 seconds. Is there a solution for this? It would be very helpful for me.

I have tried using setTimeout, but it gives me multiple results every time I type something.

<input type="text" class="form-control required-field" name="driver_fullname" placeholder="Enter fullname" v-model="formFields.fullname" v-on:keyup="typehead"/>

script

   typehead(){
        let vm = this;
        let driveInfo = vm.formFields.fullname;

         setTimeout(() => {
            axios.put(BASE_URL + '/transportation/driver/autoComplete/' + driveInfo).then(response => {
            console.log(response.data);
            });
        }, 500);
    },

Answer №1

If you're looking to optimize your user input by debouncing it and preventing excessive API calls, consider implementing a delay between keystrokes.

Take a look at the library available here: https://www.npmjs.com/package/debounce

To introduce a three-second delay after the user stops typing, one approach is to utilize clearTimeout().

Incorporate typeaheadTimeout: null into the data section of your component.

Here's how you can implement this:

handleInput() {
  let userInput = this.formFields.username;

  if (this.typeaheadTimeout) {
    clearTimeout(this.typeaheadTimeout);
  }

  this.typeaheadTimeout = setTimeout(() => {
    axios.post(BASE_URL + '/user/validate/' + userInput).then(response => {
      console.log(response.data);
    });
  }, 3000);
},

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

Bootstrap5: Left-aligned Navigation Bar Pills and Right-aligned Text

I am trying to align all my navigation pills to the left, and then add a single text element that stays at the end of the navbar even when the page is resized. Navbar Image My attempt involved adding a div so that the navbar pills would take up 50% width ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

Eliminate spacing in MaterialUi grids

As I work on a React project, I am faced with the task of displaying multiple cards with content on them. To achieve this layout, I have opted to use MaterialUi cards within Material UI grids. However, there seems to be an issue with excessive padding in t ...

Unable to utilize external JavaScript files in Angular 8

I've been working on integrating an HTML template into my Angular project and for the most part, everything is going smoothly. However, I've encountered an issue where my JS plugins are not loading properly. I have double-checked the file paths i ...

Drawbacks of adjusting design according to screen width via javascript detection

When creating a website, I want it to be compatible with the most common screen resolutions. Here is my proposed method for achieving this: -Develop CSS classes tailored to each screen resolution, specifying properties such as width and position. -Write ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Controlling dropdown menus filled with AJAX responseData

When it comes to Javascript, JQuery has always been a reliable companion for me. However, there are instances where I encounter challenges that require some extra effort to overcome. Today happens to be one of those days. I've stumbled upon an issue t ...

The asynchronous JavaScript function is successfully printing data, however it is encountering an error where it returns 'undefined'

Struggling with asynchronous calls, I've realized this question has been answered many times before. Despite trying numerous suggested approaches without success, I would truly appreciate any help. Progress has been made recently, but I still consider ...

Direct users from one path to another in Express framework

I have two main routes set up in nodejs. First is the users.js route: router.post('/users/login', function(request, response) { // Logic for user login // Redirect to dashboard in dashboard.js file after login response.redirect(&ap ...

Maximizing Content Width in FullCalendar v5 to Ensure Screen Compatibility

As I develop a calendar and timeline view using fullcalendar v5, my clients are requesting a month view that displays the entire month without any scroll bars. While I am aware of setting the contentHeight to auto, there seems to be no option for adjusting ...

Encountering a memory issue during the process of uploading an Excel File in Laravel, wherein an error is thrown stating that the allowed memory size of 536870912 bytes has been exhausted

Encountering an issue when attempting to upload an Excel File in Laravel, as it is throwing the error message: "Allowed memory size of 536870912 bytes exhausted (tried to allocate 33554432 bytes)" located in folderpath/vendor/phpoffice/phpexcel/Classes/PHP ...

Curved lines on canvas

I am currently using the stroke and path features in the canvas to create two lines, with the intention of giving them a curved, wave-like effect. I would like to achieve this without having to create an actual image in Photoshop. Is there anyone who can ...

Tips for managing a 64-bit signed integer received from a NextJS backend API

I am currently developing a NextJS application in which one of the backend API routes sends back a JSON object that includes a 64-bit signed integer. // userID represents the 64-bit signed integer res.status(200).json({ id: userId, attributes: userAttribut ...

What is the best approach to execute this function repeatedly at specific intervals?

I'm attempting to execute everything inside the checkUser() function, but it's not running at the specified interval. Is there a more efficient way to achieve this? My goal is to verify the address every few minutes. The line const accounts = awa ...

Launching a modal in a new browser window with the help of JavaScript or PHP

I need to implement a feature where clicking a link opens a modal in a new tab and redirects the current page to a different link, similar to how retailmenot handles coupons. Here is the code snippet I am currently working with: <div onClick="myFunctio ...

What are the steps to create a dynamic website using vuetify?

I am interested in creating an adaptive website using Vuetify: https://vuetifyjs.com/en/ This means there will be multiple versions of the website catered to different devices. An adaptive design will offer various designs for different screen sizes, inc ...

Exclude the node_modules directory when searching for files using a global file pattern

I'm facing some challenges setting up a karma configuration file because I am having difficulty creating a glob that correctly matches my files. Within my lerna repository, there may be node_modules folders inside the packages, and it's importan ...

Vue: Sending a function to a higher-level component

Hello there, I'm diving into Vue for the first time and trying to break down my issue as simply as possible. I currently have two components: NewsItem and NewsItemList NewsItem: <template> <div> <h1>A title</h1> < ...

Declaring module public type definitions for NPM in Typescript: A comprehensive guide

I have recently developed a npm package called observe-object-path, which can be found on GitHub at https://github.com/d6u/observe-object-path. This package is written in Typescript and has a build step that compiles it down to ES5 for compatibility with ...

delivering the optimized main RequireJS file as a static asset through NGINX servers

Is it true that serving static assets from NGINX or another server is better than using your Node.js application server? In my case, I have a single-page application where in production mode, only one optimized .js file is served from the index page, and ...