Automatically execute a function when the number input changes, but only if no further changes are detected after a certain period of time

I am implementing angularjs with an input field for numbers. I want to trigger an action automatically after a certain amount of time, but only if no further changes have been made to the number within that time frame (let's say 2 seconds).

In my example on Plunker, the action is currently being called every time the number changes. However, I would like the action to be executed only when the user has not made any changes to the value for more than 2 seconds.

<div class="col-md-3 divGridText">
    <label for="excludeMinutesStep" style="font-weight:bold">Exclude tasks &lt; </label>
    <input id="excludeMinutesStep" min="0" max="10" ng-model="excludeValue" ng-change="numericStepperChanged(excludeValue)" size="2" style="width:40px;" type="number" /> <b>minutes</b>
</div>

$scope.excludeValue = 5;
$scope.numericStepperInitValue = 0;

$scope.numericStepperChanged = function(data) {console.log("A");
  $scope.numericStepperHit = true;
  if (data != undefined) {
    $scope.excludeValue = data;
    if (data == 0) {
      $scope.isExcludeNeeded = false;
    }

    if ($scope.numericStepperInitValue == 0) {
      $timeout($scope.callAtNumercStepperChangeTimeout, 2000);
    }
  }
}

$scope.callAtNumercStepperChangeTimeout = function() {
  $scope.numericStepperHit = false;
  $scope.numericStepperInitValue++;
  $scope.changeGraph();
}

$scope.changeGraph = function() {
  if (!$scope.numericStepperHit) {
    console.log("Action called "+$scope.excludeValue);
    $scope.mytext = "Action called "+$scope.excludeValue;
    $scope.isExcludeNeeded = true;
  }
}

Answer №1

Debouncing is a common and useful pattern that you may need in your code.

An easy way to implement debouncing is by using underscoreJs debounce method:

$scope.debouncedFunction = _.debounce(myFunction, 2000);

<input ng-change="debouncedFunction()" size="2" style="width:40px;" type="number" />

If you prefer, you can also create your own debouncing function like this:

var promise = null;
function debouncedFcn{
    if(promise)
        $timeout.cancel(promise);
    var promise = $timeout(myFunction, 2000);
}

For more information, check out the Debounce documentation.

Answer №2

I created a function called timer that evaluates if a value has changed within a 2-second interval. If not, it triggers the mainFunction() which displays an alert. The timer function is then utilized in $scope.$watch to monitor changes in the excludeValue.

$scope.excludeValue = 5;

$scope.$watch('excludeValue',function(oldVal,newVal){
   if(oldVal !== newVal) // a new change 
   {
      timer(oldVal,newVal)
   }
});

var timer = function(oldVal,newVal){
   var currentVal = angular.copy($scope.excludeValue);
   $timeout(function(){
     if(currentVal == $scope.excludeValue)
     {
       // no changes made within 2 seconds 
       mainFunction()
     }
     else
     {
       // change made within 2 seconds
     }
   }, 2000);
};

timer();

var mainFunction = function(){
   alert('No changes were made within 2 seconds.');
};

You can view the code on Plunker

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

Preventing variables from reinitializing in express.js

Within my app.js file, I invoke a search function that communicates with an LDAP server. Upon doing so, the server sends back a cookie which is essential for my subsequent queries. My intention was to save this cookie as an app.local variable in my app.j ...

Encountering an Unexpected Error in Next.js When Revalidating Paths

I'm facing an issue with my Next app where, despite editing a resource through an API endpoint following the pages-based system, the changes aren't reflected when I try to view or re-edit the resource. After checking the documentation, I discover ...

I'm attempting to create a button that changes to a bold red color when the condition is met

I am currently working on developing web applications using the Pixabay API. My goal is to allow users to mark an image as a favorite and have the heart icon change color to red accordingly. However, I seem to be facing issues with this functionality. To ...

Place a new button at the bottom of the react-bootstrap-typeahead dropdown menu for additional functionality

Currently, I have successfully implemented the React Bootstrap Typeahead with the desired options which is a good start. Now, my next challenge is to integrate a custom button at the end of the dropdown list for performing a specific action that is not ne ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

Is it possible to update the state of an array within a .then() function in React?

` After retrieving an array of points with city and state information, I attempted to convert these points to latitude and longitude by making a fetch call. However, upon trying to update the state of the newly generated array, I found that it remained ...

The JavaScript code is failing to retrieve the longitude and latitude of the location on a mobile browser

I am having an issue with my Javascript code not properly retrieving the longitude and latitude from the mobile Chrome browser. While this code works fine on laptop or desktop browsers, it seems to be failing on mobile devices: <script> if (nav ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

Fetching user feeds from Facebook with AngularJS is easier than you think

I have searched through multiple articles but have yet to find a solution for this particular issue. My goal is to retrieve user feeds from Facebook. How can I achieve this? Below is my code: var newMod = angular.module('newapp', []); newMod.c ...

Using " " to split a name into two lines is not being recognized

My issue involves the display of tab names in two lines within multiple tabs. You can view the demonstration here. I attempted to use the \n character while setting the tab name but it was not recognized. Any suggestions on how to achieve this? Here ...

Duplicate user scrolling input within a specified div container

I am attempting to recreate a horizontal scrolling effect on a div element that mirrors the input scroll. When the user scrolls along the input, I want the div element to scroll in sync. The issue I am encountering is specific to Chrome, where the input b ...

Troubleshooting: Unable to Display Image and Text in Ionic View Header

I have successfully created a code snippet that allows me to attach an image and text to the header bar of an Ionic view. Here is the code: <ion-view align-title="left"> <h1 style="margin-left:100px" class="title"> <img class="title-image" ...

Unable to access npm run build on localhost

I have developed a web application using react and node.js, and now I want to test it with a production build. After running npm run build in the app directory, I successfully created a build folder. However, when trying to run the application using local ...

Attempting to showcase extensive content based on the selection made in a drop-down menu

As a newcomer to anything beyond basic HTML, I am seeking guidance and assistance (preferably explained at a beginner level) for the following issue. If I have overlooked any crucial rules or concepts in my query, I apologize. I aim to have each selection ...

most efficient method to execute numerous API requests at the same time

Currently, I am developing a backend using expressJS. Imagine that I need to make 10,000 calls to an API consecutively and store the obtained data in a database. What would be the most effective approach for achieving this task? Is it possible that Promis ...

Utilizing Rails to incorporate a comment box through jquery on individual posts within a index page showcasing all listed posts

As I display a list of posts on my index file, I want each post to have its own comments section. To achieve this, I have added a "Show Comments" button for each post. However, when I click the button, jQuery triggers all comment boxes on the page instead ...

Calling a function within another function

In my code, I have a function that formats the price and retrieves the value needed for refactoring after upgrading our dependencies. I'm struggling with passing the form value to the amountOnBlur function because the blur function in the dependencie ...

How can I retrieve the width of a responsive React element during its initial rendering phase?

In my React project, there is a component called ResultList which is used to display products in a gallery format. The challenge I'm facing is determining the appropriate number of products to show per row based on the available width for the ResultL ...