Trigger the input with a delay function, pause if the input value is modified

I am in the process of creating an angular directive that will run a function when the input value changes. I want to implement a 300ms delay before running this function, but if the value changes again within the 300ms timeframe, I need to reset the delay back to 300ms. Therefore, the function should only be executed after the value has remained unchanged for 300ms:

Here is my code snippet

(function() {
    'use strict';

    angular
    .module('address',[])
    .directive('address', ['Address', function (Address) {
      return {
        restrict: 'E',
        transclude: true,
        templateUrl: 'partials/address.html',
        link: function (scope, elem, attrs) {
            var delay = "300";
            scope.$watch('searchparam', function(){
                if(!_.isUndefined(scope.searchparam) && scope.searchparam.length >= 3) {
                    // Implementing a delay timer here
                    Address.get(scope.searchparam).then(function(data){
                        console.log("data: ", data);
                        scope.addressList = data;
                    }, function(status){
                        console.log("status: ", status);
                        scope.errorHandler = status;
                    });
                }
            }); 
        }
      };
    }]);
})();

The address.get function is an asynchronous service that returns addresses.

Answer №1

If you're looking to optimize your JavaScript code, consider implementing a debouncing technique. This is a common practice in various JS libraries and has even been recognized as standard in AngularJS 1.3.

Answer №2

Here is an example of what you might need:

let delay = "300"; // This is just a placeholder for the rest of your code :)
let timeout;
scope.$watch('searchparam', function(){
    if(!_.isUndefined(scope.searchparam) && scope.searchparam.length >= 3) {
        function retrieveAddress() {
            // Perform necessary actions to get address - Address.get(...
        }
        if (timeout) // Attempt to clear the timeout if it was set before
            clearTimeout(retrieveAddress);
        timeout = setTimeout(retrieveAddress, 300); // Reset timer

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

Using AngularJS to send a request to Devise (backend) for resetting a password

I need assistance implementing password reset functionality from AngularJS (front end) to Rails (back end). Currently, the JSON I am sending does not match the hash structure that would typically be sent from a pure rails application, and I have been stru ...

A collection nested inside another collection

In my quest to create a program for tracking a baseball card collection, I came up with the idea of simulating buying packs of 7 cards in order to complete a total collection of 500 unique cards. Each card is assigned a value between 0 and 499, and I dev ...

What is the best way to ensure that text only displays up to five lines and fully collapses using CSS or javascript/jquery?

Hello everyone, I have come across an issue. English is not my strong suit, but I will do my best to explain it thoroughly. The problem at hand is a design requirement in the draft that specifies showing up to five lines of text. If the text exceeds this ...

How can the Angular Js framework be utilized to create a pop-up feature in combination with Bootstrap?

I'm currently working on a website using AngularJS and Bootstrap. When the site is loading, I make a server call to fetch some data. This process takes some time, and during this interval, I want to display a pop-up message indicating that the user s ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

Observing a two-way binding in AngularJS directive with the $watch functionality

I am currently working on differentiating between internal changes and external changes using a two-way data-bound attribute ('='). To clarify: I want to prevent $watch from triggering if the change was made internally (such as altering the scop ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows: function statusChangeCallback(response) { ...

How can I eliminate the apostrophe from the hidden field's value using JavaScript?

Currently, I am using JavaScript to read a hidden field value. However, the value I am obtaining is wrapped within single quotes ('78963'). How can I eliminate this single quote and retrieve the value without it (78963)? Any assistance in resolvi ...

Leveraging configuration files in AngularJS

I'm working on an Angular application that communicates with a Node.js backend Express application. I am using a config file to store environment variables for my Node app. Here's how I access the config file in my Node app: index.js var port = ...

What are the steps to ensure the equalizer start button functions properly?

I have created an application that mimics the functionality of an equalizer by displaying changes in audio frequencies. https://i.sstatic.net/W7Fzi.png Issues with animation arise when you click the "Start" button again. The animation resets and begins ...

Update the class of the appropriate navigation tab when the corresponding div is scrolled into view

After reading similar questions and doing some research on scrollspy, I don't think it will provide the functionality I need. It seems to only support bootstrap style highlighting. If there is more to it that I'm not aware of, please inform me! ...

Extract particular elements from a nested JSON response in order to convert them into a string

I am currently integrating Microsoft Azure Cognitive Services text recognition API into a JavaScript web application. After successfully extracting text from an image, the response looks like this: { "language": "en", "textAngle": 0, ...

Is there a way to enclose a portion of text within an element using a span tag using vanilla JavaScript?

Imagine having an element like this: <p id="foo">Hello world!</p> Now, the goal is to transform it into: <p id="foo"><span>Hello</span> world!</p> Is there a way to achieve this using pure vanilla J ...

Is it possible to incorporate a YouTube video into a webpage without displaying any external links to YouTube above the video player?

Looking for a solution to embed a YouTube video on my webpage without the link appearing when hovering over it and without the suggested videos at the end. Just the option to replay the video without the distraction of related videos. ...

Deciphering the Components of Web Applications: Express.js, Angular.js, and the MVC Puzzle

After exploring numerous discussions on Stack Overflow regarding the integration of Express.js with Angular.js and the presence of dual MVC components in both the client and server sides of web applications, I have found myself feeling somewhat perplexed. ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

What is the best way to display JSON response as code instead of a string in AngularJS?

When retrieving my article from the database as a JSON object, I encounter an issue with the body content. The HTML codes in the body are displayed as strings within double quotation marks by AngularJS. How can I resolve this? Angular controller snippet: ...

Using Echarts markLine feature with series that are stacked together

As I attempt to place two line series at the top of a graph using the markLine option, I encounter an issue. The line series are stacked, but when I apply a markLine with the type: max option, the markLine on the top graph appears below the graph because t ...