Setting a timeout for polling in JavaScript or Angular

function checkForNotifications(id) {    
    $http({
            method: "POST",
            url:( "url"),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            data: $.param({id: id}),
        })
            .then(notificationCheckComplete)
            .catch(function(message) {
                throw new Error("XHR Failed ",message);
            });

        function notificationCheckComplete(response, status, headers, config) {
            //perform actions based on response, display errors, show popups, etc.
        }
  setTimeout(function() {checkForNotifications()}, 1000);
}

This code is designed to periodically poll the database for new notifications.

I do not clear the timeout and do not use $timeout. Could this lead to issues such as Chrome freezing or high CPU usage?

How can I properly clear the timeout and verify that it has been cleared?

All functions and UI elements are part of an Angular service/factory without a controller (except for the service call).

Answer №1

In order to execute the scanComplete function, you should only invoke it again within this specific function.

function scanComplete(response, status, headers, config) {
    //perform actions such as displaying errors, popups, or calling other functions
    setTimeout( scan, 1000); //invoke after your ajax is complete
}

By following this approach, you will guarantee that only one instance of the scan function is running at any given time.

I don't clear the timeout at all and I do not use $timeout. Could this be a mistake? Will it lead to issues like freezing or excessive CPU usage in Chrome?

As long as you are only triggering one instance of the scan function sequentially, there shouldn't be any concern regarding CPU overhead or performance issues.

Answer №2

If you want to handle the $destroy event in your main controller, you can create a function in your service that clears a timeout when the event is triggered:

module.factory("myService", function($scope, $timeout) {
     
  var timer;
     
  function startTimer() {    
    // $http......
    timer = setTimeout(function() {startTimer()}, 1000);
  }

  function clearTimer() {
      if (timer) {
          $timeout.cancel(timer);
      }
  }
 
  return {
     clearTimer: clearTimer,
     // ...
  }

});

module.controller("MainController", function($scope, $timeout, myService) {
  $scope.$on("$destroy", function() {
      myService.clearTimer();
  });
});

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

Navigate to the following tabindex after submitting the form again

How can I enhance the user experience by allowing them to easily update generic names (name1, name2, name3) with more meaningful ones without being redirected back to the previous name? Look for the comment WHAT GOES HERE? below. Example HTML layout: < ...

Manipulating and inserting objects into an array using React and Typescript with an undefined type

As I embark on my TypeScript journey in React, I decided to test my knowledge by creating a simple Todo App. Everything seems to be working fine except for one issue! After adding a new task and hovering over it, I received the following error message (tr ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

Craft a JavaScript script (empowered by selenium) that endures through page reloads

In the process of developing a macro recording and playback system utilizing selenium and JavaScript, I encountered an issue. Essentially, I have implemented a JavaScript code that attaches a new event handler to all window events, capturing and storing ev ...

Keep an ear out for updates on object changes in Angular

One of my challenges involves a form that directly updates an object in the following manner: component.html <input type="text" [(ngModel)]="user.name" /> <input type="text" [(ngModel)]="user.surname" /> <input type="text" [(ngModel)]="use ...

JavaScript does not recognize Bootstrap classes

I am utilizing Bootstrap 5.3.0 and have included it through CDN links in my JS script. This is how I am injecting it using my js file within the existing website's DOM via a chrome extension named Scripty, which serves as a JS injector extension for c ...

Extension for Chrome - view source of current webpage

I'm attempting to develop my chrome extension to extract the current page source and identify the current URL, as seen in this example. If I were to visit https://www.google.com and the page source contains google I want my extension to display a ...

How can I extract and display data from a MySQL database in cytoscape.js?

I have a database table called 'entrezgene' that contains geneID and name fields. These fields will be used to create nodes in cytoscape.js. Additionally, I have another table named 'interaction' with geneID and geneID2 fields, which wi ...

Error in JSON Format Detected in Google Chrome Extension

Struggling with formatting the manifest for a simple Chrome extension I'm developing. I've been bouncing back and forth between these two resources to try and nail down the correct syntax: https://www.sitepoint.com/create-chrome-extension-10-mi ...

The Project_Name index has not been defined

I'm attempting to tally up all of my projects in the project table, with Project_Name being a column name. Below is the code I've tested: <?php $sql = "SELECT COUNT(*) FROM project"; $result = $connection->query($sql); if ($res ...

Navigating Promise.all effectively: Understanding the issue of receiving undefined

I'm currently working on fetching data from multiple REST APIs and storing it in an array. While attempting to use Promise.all for this purpose, I encountered an issue where the resulting array contains a series of undefined. [ undefined, undefine ...

Different width, same height - images arranged side by side in a responsive layout

The problem lies in the images: https://i.sstatic.net/rydNO.png Here is an example of desktop resolution: https://i.sstatic.net/uv6KT.png I need to use default size pictures (800x450px) on the server. This means I have to resize and crop them with CSS to ...

The current state of my DOM doesn't match the updated value in my model. The update is triggered by a function that is called when a button is clicked

app.controller('thumbnailController', function ($scope) { debugger $scope.customers = [ { name: 'Ave Jones', city: 'Phoenix' }, { name: 'Amie Riley', city: 'Phoenix&ap ...

Providing the module with the URL

How can I retrieve the URL within a module? module.exports = function(app, Reviews, Anon, User, url){ var url = url; console.log("url", url)// url is undefined how to get url function postHandler(req, res){ } app.post("/individual/"+ u ...

Guide to organizing elements in an array within a separate array

Our array consists of various items: const array = [object1, object2, ...] The structure of each item is defined as follows: type Item = { id: number; title: string contact: { id: number; name: string; }; project: { id: number; n ...

How can I use a button to save all changes made in a JqGrid checkbox column simultaneously?

In my jqgrid, there is a column named 'asistencia' which displays data from a database as checkboxes. These checkboxes are pre-checked based on the property formatoptions: {disabled : false}. I would like to implement a 'save' button th ...

"Exploring the transition from traditional polling to the enhanced experience

I have a script that utilizes basic polling to display the total number of records in the database in real-time. Can anyone provide an example of converting my code into a long polling structure using plain JavaScript? I've searched on Google but all ...

Look for specific terms within an array of words

Hello, I am facing a challenge with searching for words that contain at least part of another word in JavaScript. Specifically, I need to find words in an array without using built-in functions like index.of, slice, substr, substring, or regex. Can only us ...

The React JSON Unhandled Rejection problem requires immediate attention

While working on a form in React 16, I reached out to a tutor for some guidance. However, when trying to mock the componentDidMount, I encountered an error that has left me puzzled. The app still runs fine, but I am curious as to why this error is occurrin ...

Troubleshooting problem with binding and calling jQuery javascript functions

I created a custom JavaScript function called 'mc_change' and I want it to be triggered when a textbox's value changes. <input type="text" id="mc_val" onchange="javascript:mc_change();" /> Unfortunately, the function is not working ...