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

Steps for making a webpack-bundled function accessible globally

I am currently working with a webpack-bundled TypeScript file that contains a function I need to access from the global scope. Here is an example of the code: // bundled.ts import * as Excel from 'exceljs'; import { saveAs } from 'file-save ...

When I receive a 404 response from the API, I aim to start my observable

How can I trigger my observable initialization when receiving a 404 response from the API? The code snippet below is not working as expected. const urlParams = { email: this.email }; this.voicesProfileObservable$ = this.service.request<any>( AVAI ...

Tips for selecting a JSON data node on-the-fly using jQuery

This is an example of my ajax function: $.ajax({ type: "GET", dataType: "json", async: false, url: "/wp-content/comment_data.php", data: 'songid=' + $array, success: function(data){ oTable.find('td').eac ...

What could be causing React to throw an error?

Check out this React Component: GeneralInformation = React.createClass({ totalCaptialRaisedPanel: function() { var offeringInfo = this.props.company.data.offerings.data[0]; var percentageComplete = (offeringInfo.capital_raised / offer ...

What are the potential causes of receiving the error message "No Data Received ERR_EMPTY_RESPONSE"?

I often encounter this issue on my website, especially when I have a thread open. It seems to happen whenever I am actively checking for new posts and notifications via Ajax every 10 seconds or so. However, I'm not sure if this continuous reloading is ...

Maximizing the potential of .delegate in combination with .closest

$('.inputRadio').parent().click(function (e) { //implement delegate method here }); Looking for assistance on how to integrate the delegate method in the provided function. Any suggestions? ...

Automatically close the popup each time it is displayed (using jQuery/JavaScript)

I am having issues with auto-closing my popup each time I open it. The current code I have only closes the popup the first time, requiring me to refresh the browser in order to auto-close it again. Can someone please assist me in writing a new code that ...

Unique syntax using markdown-react

I want to customize the syntax highlighting in react-markdown. Specifically, I would like to change the color of text inside {{ }} to blue while still maintaining the correct formatting for other elements, such as ## Header {{ }} import React from " ...

I'm curious about the meaning of "!" in pseudo-code. I understand that it represents factorial, but I'm unsure of how to properly interpret it

Can someone explain the meaning of ! in pseudo-code to me? I understand that it represents factorial, but for some reason I am having trouble translating it. For example: I came across this code snippet: if (operation!= ’B’ OR operation != ’D’ O ...

Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON: var names= [ { "category":"category1" , "name1":"david", "name2":"jhon", "name3":"peter" }, { "category":"catego ...

Why is my return statement in JavaScript Nextjs mapping values twice?

I am running into an issue where my code is displaying the output twice, and I can't seem to figure out why. Any assistance would be greatly appreciated. Here is a link to the current output that I am receiving. I suspect that the problem lies in sett ...

AngularJS: Automatically refreshing ng-repeat based on checkbox filter updates in code

I have a container that is populated using ng-repeat="item in items | filter:isselected(item)". To filter the items, I have checkboxes with ng-model="selecteditem[$index]" and a filter function $scope.selectedItems = []; $scope.isselected = function(item ...

How can I show the <md-progress-linear md-mode="indeterminate"> when a button is clicked?

To track the progress of uploading a file, I need to show a progress bar. However, this progress bar should only appear after clicking on the Upload button. Let's get started with the upload process! ...

Utilize the _sortBy function from the lodash library to arrange an array based on a specific field

Looking at an array of objects similar to this: myArray = [ {AType: "aaa", Description: "De", …}, {AType: "bbb", Description: "Hi", …}, {AType: "ccc", Description: "Un", …}, {AType: "ddd", Description: ...

I'm wondering, on a storybook, where is the best place to set my MUI X license key

Can you help with where to specify my license key in Storybook? I need guidance on where to set the license key in Storybook. According to MUI Docs, it should be done before React renders the first component and only once in the application. However, I ...

Display live data directly from a specific XML tag on a webpage

My project involves working with a local XML file that is being constantly updated by a third party. I am looking to create a web page that can dynamically read and display a specific XML tag without requiring the page to be refreshed. Additionally, I woul ...

What is the best way to retrieve the value from a PHP request?

I am encountering an issue with a multiselect form field named properties[]. When I attempt to retrieve the values in my controller using dd($request->get('properties')), it gives me ["1,2"]. However, trying to access the first ele ...

Obtain the AJAX response in separate div elements depending on whether it is successful or an error

Currently, my jQuery script outputs the result in the same div for error or success messages: HTML <div id="error-message").html(res); JQUERY jQuery('#register-me').on('click',function(){ $("#myform").hide(); jQuery ...

Creating custom validation in AngularJS using CSS styling Incorpor

I need help figuring out how to display an error message when the field input is invalid. I can see that the correct classes are being applied to the element, like ng-dirty ng-invalid ng-invalid-pattern, so now I just need to make sure the error message sh ...

Shuffle the JSON data before displaying it

Just a heads up, the code you're about to see might make you cringe, but I'm doing my best with what I know. I've got a JSON file with a bunch of questions, here's what it looks like: { "questions": [ { "id": 1 ...