Tips for preventing multiple requests in your JavaScript search autocomplete feature

I'm currently using the Turbolinks.visit action with the help of $(document).on("input");...

HTML

<form id="mainSearch" method="get" autocomplete="off">
    <input type="search" name="s" placeholder="Search" />
</form>

Javascript

$(document).off().on("input", "#mainSearch", function(e) {

        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();

        var searchQuery = $(this).serialize();

        setTimeout(function(){
            Turbolinks.visit(
                homeurl+"/?"+searchQuery,
                {
                    change: ['content']
                }
            );
        },110);

        return false;
    });  

Everything seems to be working correctly, but multiple requests are triggered when holding down a key.

https://i.sstatic.net/fP8PE.png

How can I prevent it from sending multiple requests while keeping the key pressed? .on("input"

Answer №1

Did you accidentally neglect to stop the previous timer?

let myTimer = null;

$(document).off().on("input", "#mainSearch", function(e) {

    e.stopImmediatePropagation();
    e.stopPropagation();
    e.preventDefault();

    let searchValue = $(this).serialize();

    clearInterval(myTimer);

    myTimer = setTimeout(function(){
        Turbolinks.visit(
            homeurl+"/?"+searchValue,
            {
                change: ['content']
            }
        );
    },110);

    return false;
});  

Edit: Instead of starting from scratch, it's wise to utilize existing solutions like $.debounce().

Answer №2

If you're utilizing JQuery, consider checking out this solution which uses $.debounce

For some hands-on practice, feel free to explore these examples on http://jsfiddle.net/cowboy/cTZJU/

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

The Outer Div Can't Contain Google Maps

I am currently working on integrating a map widget into a dashboard I created using gridstack.js. The sample widget layout that I am aiming for can be seen in the link below: https://i.sstatic.net/ZQP6G.png My goal is to embed the map within the inner (w ...

Freezing Columns and Rows for a Spacious Scrollable Table

After extensive effort, I have been diligently striving to create a solution that allows a table's column headers to scroll with the body horizontally and the first column to scroll with the rows vertically. While I've come across solutions that ...

I am experiencing difficulty deleting a post due to unknown errors. Is there a way to successfully remove data from the database using the DELETE command?

Here are the two issues I'm encountering. MongooseError [CastError]: Casting to ObjectId has failed for value "{item._id}" at path "_id" for the model "Post" Second Error stringValue: '"{item._id}"', kind: 'ObjectId', value ...

Creating objects with variable-dependent values in node.js

I'm currently working on creating a user database in an object to assign values to each user, but I'm struggling to find a way to accomplish this. I attempted using var data = {} and then eval(`data.user_${user} = value`), however, it only write ...

Utilize a traditional JavaScript class to instantiate an object in Vue.js

Is it possible to integrate a standard JavaScript class into a Vue.js component without needing anything static? If not, I am open to switching to React or Angular. Are they more suitable than Vue.js for code reusability? Test.js file: class Test { co ...

Serving pages with Node JS and loading .js files on the client side

Here is a simple JS file that will be familiar to those who have worked with Socket.IO in NodeJS and Express: var express = require('express'), app = express(), server = require('http').createServer(app), io = require(&apos ...

Using JavaScript, concatenate text from each line using a specified delimiter, then add this new text to an unordered list element

I am looking to extract text from named spans in an unordered list, combine them with a '|' separating each word within the same line, and append them to another ul. Although my code successfully joins all the words together, I'm struggling ...

Eliminate the alert message that appears when dynamically rendering a React styled component

When checking the browser console, I noticed a warning that reads as follows: react_devtools_backend.js:3973 The component styled.div with the id of "sc-dmRaPn" has been created dynamically. You may see this warning because you've called sty ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Problem with javascript querystring code

Currently in the process of writing some vanilla JavaScript code to manipulate query strings without using jQuery. Here's what I have so far: // If there is no viewid in the query string, append it as a new key if (newUrl.indexOf("viewid") == -1) { ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Evaluating QUnit Test Cases

How do you write a test method in QUnit for validating functions developed for a form? For example, let's consider a form where the name field should not be left blank. If the validation function looks like this: function validNameCheck(form) { if ...

When dynamically loading content with ajax, dynamic content fails to function properly

Currently, I am attempting to incorporate dynamic content loading after the user logs in by utilizing $.ajax. Here is how it's being done: $.ajax({ url: "functions.php", type: "GET", data: login_info, datatype: 'html', a ...

Hide the load more button when there is no additional content available for Ajax loading

Currently, I am working on a WordPress query for a custom post type and would like to implement a "load more" button using Ajax to allow users to load additional articles. To handle the scenario where there are no more posts to load, I have included an "el ...

Steps to turn off popover functionality for a specific child element

Within a container, there are details along with a button. The container exhibits popover behavior upon hovering over it. However, the challenge lies in disabling the popover behavior while hovering specifically over the button within it. You can find th ...

How do I insert a variable into my email content using PHP?

Hey there, I have a form that captures Name, Email, Subject, Telephone Number, Message, and a checkbox. Unfortunately, I'm not very proficient in PHP. I've just started learning the basics and could use some guidance from you :) The Form < ...

Sequelize associations are not functioning optimally as expected

Trying to display a nested relationship: Cat.hasMany(legs) Leg.belongsTo(cat) Leg.hasOne(paw) paw.hasMany(leg) This is the Cat Model: module.exports = (sequelize, DataTypes) => { const Cat = sequelize.define('Cat', { us ...

The catch block seems to be failing to capture the errors thrown by the fetch API

I am facing an issue with my code where the fetch method, enclosed within a catch block, fails to capture errors. Despite attempting various error handling approaches on my node backend, the problem persists. https://i.stack.imgur.com/0reJj.png const e ...

Retrieve information from a text

I retrieved this data as a string from a webpage using jQuery and need help parsing it. When I attempted to use jQuery.parseJSON, I encountered the error Uncaught SyntaxError: Unexpected token n. The specific values I am looking for are "surl" and "imgur ...

The concept of overloading operators in V8

Here's a question that I've been pondering, but couldn't seem to find any answers for on Google. While it may not be achievable in pure JavaScript, let's say I'm developing a container class in V8 and then returning that class bac ...