Ending a timed function in AngularJS 1

As part of my Angular JS 1 learning journey, I am working on a small test involving text areas that display text using Angular functions when a user enters and exits them. The enter function has a 3-second delay, while the exit function waits for 5 seconds. It's all functioning as expected at the moment.

The challenge now is to prevent the functions from binding text to the text area if the user does not wait for the specified timeout periods. I believe promises might be the key here, but I'm struggling with this aspect.

var myApp = angular.module('myApp', []);

function checkTimeout() {
  console.log("Timeout is working...");
}

myApp.filter('rawHtml', ['$sce', function($sce){
   return function(val) {
   return $sce.trustAsHtml(val);
  };
}])

myApp.controller("MyCtrl", function($scope, $timeout){

$timeout(checkTimeout, 3000);

$scope.data = [{
  "id": 1,
  "act": ""
}, {
  "id": 2,
  "act": ""
}, {
  "id": 3,
  "act": ""
}, {
  "id": 4,
  "act": ""
}, {
  "id": 5,
  "act": ""
}, {
  "id": 6,
  "act": ""
}, {
  "id": 7,
  "act": ""
}, {
  "id": 8,
  "act": ""
}, {
  "id": 9,
  "act": ""
}];

$scope.enter1 = function(num) {
  $timeout (function(){num.act = " - enter";}, 3000 );
}

$scope.exit1 = function(num) {
  $timeout (function(){num.act = " - exit";}, 5000 );
}


})

HTML:

<body ng-app="myApp">
  <div ng-controller="MyCtrl" style="width:100%;margin:10px;">
      <p>How can I stop the functions enter1 and exit1 from binding text to the textarea if the user does not wait the 3 seconds (enter1) and 5 seconds (exit1) for them to execute?</p>
      <div style="float:right; width:49%;">
        <div ng-repeat="num in data" style="margin:3px;">
          <textarea ng-focus="enter1(num)" ng-blur="exit1(num)">{{ num.id }}{{ num.act }}</textarea>
        </div>
      </div>
  </div>
</body>

Here's the fiddle: https://jsfiddle.net/mediaguru/q3qt5frk/

Answer №1

Utilizing the $timeout function creates a timer that can be manipulated.

let newTimer = $timeout(handleTimeout, 3000);

//Stop it
$timeout.cancel(newTimer);

Answer №2

To prevent memory leaks, it's crucial to clear all timers. Ensure that you clear the timer if the element that triggers it is destroyed. In Angular, each element has a scope, and calling $scope.$destroy() will notify when the scope of a specific element is destroyed, requiring you to clear all timers and events.

var timerList = new Array();
...
// add a timer to the list
timerList.push(setTimeout('someFunction()', 1000));
...
// clear all timers in the list
for (var j = 0; j < timerList.length; j++)
{
    clearTimeout(timerList[j]);
}

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

Is there a way to export a specific portion of a destructuring assignment?

const { a, ...rest } = { a: 1, b: 2, c: 3 }; If I want to export only the rest object in TypeScript, how can I achieve that? ...

Issue with redirecting after a POST request is not functioning properly

After creating an API in node and defining a method to handle POST requests, I found that returning res.redirect(redirectUrl); from the method causes the browser to redirect back to the API instead of the intended URL. Despite my efforts, this issue persi ...

What is the best way to ensure input values are automatically set as empty (rather than "undefined") when the user deletes the value?

When using Angular 1.6, if a user deletes the content inside an input field, the value is set to "undefined" by default in AngularJS. HTML <input ng-model="name" class="form-control" id="inp_name" placeholder="My Name" required="true" value="" ...

Leveraging a specially designed function within an equation

After creating a function called calculateObjectDepth(object) that determines the depth of an object and returns a corresponding string (for example, if the depth is 3, it will return "sub-sub-sub"), I realized that in my directive template, I need to util ...

Using jQuery to toggle the visibility of table data cells across various tables on a single webpage

On my webpage, I have multiple tables and I'm trying to add more rows or close table data cells using jQuery. However, I seem to be encountering an issue as it's not working properly. <table class="table" ><tr> < ...

Exploring the capabilities of Three.js Projector and Ray components

Recently, I've been experimenting with the Projector and Ray classes for collision detection demos. My main focus has been on using the mouse to interact with objects by selecting or dragging them. While studying examples that utilize these classes, I ...

Is there a way to change my curl command into an AngularJS HTTP request?

Looking to translate the following curl command into an Angular http request. The command appears as follows: " curl -X POST --data 'username=myusername&password=mypassword' -i " When using HTTPS, should I use GET or POST? Any assistance w ...

Ensure that when adjusting the height of a div, the content is always pushed down without affecting the overall layout of the page

My webpage contains a div element positioned in the middle of the content, with its height being adjustable through JavaScript code. I am seeking a way to manage the scrolling behavior when the height of the div changes. Specifically, I want the content t ...

Efficient React search feature with pagination that avoids redundant setState calls

Currently in the process of incorporating search functionality with pagination in React. After reviewing numerous examples, it appears they all involve using setState() twice, both before and after making an AJAX call to the backend. Here is a snippet of m ...

Adjust the size of an array based on the specified index

I have an array defined as... let myArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] ...along with a starting index let start = 2 and an ending index let end = 5. I want to resize the array by taking elements from start to end, for example: start ...

What is the best approach to retrieve a JSON object from a form exception that has a specific name?

I have a certain form with input fields. My goal is to generate a JSON object from the form, excluding any input whose name is "point". However, my code doesn't seem to be working properly when I use the "not()" function. What am I doing wrong and how ...

Receiving notifications about a user's location when they interact with points of interest

My goal is to find nearby establishments based on points selected by the user on a map through clicks. I successfully implemented a click handler on the map using google.maps.event.addListener to retrieve the lat/lng of the clicked location. The issue ari ...

The JavaScript Autocomplete feature fails to clear suggestions when there is no user input detected

After watching a tutorial on using Javascript with Autocomplete and a JSON file, I implemented the code successfully. However, I encountered an issue: When I clear the input field, all results from the file are displayed. I've tried adding code to cl ...

Using React client to accept messages from a Socket.io server: A guide

I have a setup where a Node.js server with Socket.io is used to send messages between React clients. Currently, I can send a message from Client 1 to Client 2, but the recipient must click a button to view the message on their screen. I am trying to make i ...

The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify th ...

Unable to retrieve the length of HTMLCollection

I've been having an issue with accessing all the dynamically created list elements (<li>) on my page using getElementsByTagName. The console keeps showing that the length of my li array is 0. Despite going through documentation and examples rel ...

Converting and downloading CSV to XLSX directly from the front end using TypeScript and React

After successfully converting a JSON response to CSV format for download using the function below, I am now looking to achieve the same functionality but with xlsx files on the front end. The current function works well for CSV files and handles Japanese ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

The browser is throwing errors because TypeScript is attempting to convert imports to requires during compilation

A dilemma I encountered: <script src="./Snake.js" type="text/javascript"></script> was added to my HTML file. I have a file named Snake.ts which I am compiling to JS using the below configuration: {target: "es6", module: "commonjs"} Howeve ...

Formulate a multi-line string using a collection in React's JavaScript framework

I'm working on a React function that involves a set and I need to update an HTML element using the data from this set. Below is an example of my code: const updateElement = (mySet) => { document.getElementById('myId').innerHTML = Arra ...