The callback function within the Service does not execute just once when utilizing $timeout

Looking to implement a service that functions similarly to this example. Here is the code I have so far:

app.service('Poller', function ($q, $http, $timeout) {

var notification = {};
notification.poll = function (callback, error) {
    return $http.get('https://someapi.com').then(function (response) {
        if (typeof response.data === 'object') {
            if (callback){
                callback(response.data);
                console.log('tick');
            }
        } else {
            if (error) {
                error(response.data);
            }
        }
        $timeout(notification.poll, 10000);
    });
}

notification.poll();

return notification;
});

In my controller, I am using it like this:

Poller.poll(
    function(jsonAPI) { 
        console.log(jsonAPI);
    }, 
    function(error) {
        console.log('Error:', error);
    }
);    

The data is being retrieved correctly, but there are a couple of issues:

  1. The callback function only gets called once and not at the specified $timeout interval. Adding conditionals in the service for callback and error handling prevents an error from occurring (callback is not a function). When I refresh or change the view, the callback function is triggered again.
  2. The $timeout seems to be firing twice every 10 seconds instead of just once.

Answer №1

Implement the following code snippet:

$timeout(function () {
    notification.poll(callback, error);
}, 10000);

in place of

$timeout(notification.poll, 10000);

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

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

What is the best way to show distinct items and their frequencies from an array of objects in Vue.js/JavaScript?

I have been developing an inventory management application using Vuejs, and I am facing a JavaScript-related challenge in my project. The issue revolves around handling data that includes user information retrieved from a form, as well as static categories ...

What is the best approach to retrieve a recently upserted document in MongoDB?

When executing the command below, with foos representing a collection, I perform an "upsert" of a new item: foos.update(criteria, { $set: fooUpdate }, { w: 1, upsert: true }, function(err, upsertedFoo) { /* upsertedFoo represents the count of ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

Nested routes are arranged in the depths and a variety of components appear depending on the path of the

I've encountered a situation where I have deeply nested routes in my routes.js file. The code snippet below shows that depending on the route, I need to render different components. For instance, if the route is for products, I should render the Produ ...

Tips for retaining the selected radio button in a Java web application even after a page refresh

As someone new to web development using the Stripes Framework, I am encountering an issue with radio buttons on a webpage. When one of the radio buttons is selected, a text box and Submit Button appear. After clicking the Submit button, the functionality ...

Using class binding for both ternary and non-ternary attributes

Suppose we have a tag that utilizes a ternary operator to apply alignment: <td :class="alignment ? ('u-' + alignment) : null" > This functions as intended since the pre-defined alignment classes are in place, now if we want to ...

Having difficulty attaching events to Bootstrap 3 button radios in button.js

Struggling with extracting the correct value from a segmented control created using the radio button component of button.js in Twitter Bootstrap 3. Upon binding a click event to the segmented control and running $.serialize() on its parent form, I noticed ...

Insert JavaScript code into the head of the document (including the complete script code)

I am looking to insert a script in the head section of a website so that the target HTML appears as follows: <head><script type="text/javascript">*some code...*</script></head>. This particular script works perfectly: var head = d ...

Unable to change data in table TD using AJAX and PHP received JSON array

I am currently facing an issue with a PHP-AJAX script that is responsible for deleting financial rows from a table. The PHP script is functioning correctly and successfully deleting the rows. However, the problem arises within the success function of the A ...

Create personalized styles for each item within a stack with specific spacing using the @mui library

Is there a way to change both the background color and spacing area when hovering over each item in my list? https://i.stack.imgur.com/87TST.png <Stack spacing={4} divider={<Divider variant={`fullWidth`} orientation={`horizontal`} flexItem/>}> ...

Creating a Gulp automation task to handle ng-constant across various environments

I've been attempting to make this work, but it seems like I might be overlooking something. I'm utilizing ng-constant and configuring different environment endpoints as outlined in the ng-constants issue However, my setup involves using gulp and ...

The issue of empty req.body in POST middleware with Medusa.JS

Feeling completely frustrated with this issue. Grateful in advance to anyone who can lend a hand. Any insights on why req.body is showing up empty? Medusa.JS should be utilizing bodyParser by default, correct? It was functioning fine earlier today but now ...

I just finished crafting a dynamic line chart with d3.js within a React environment. However, I am now looking to add some personalized touches to enhance its appearance. Could you kindly review the details and code

I want to create a line chart using React and D3, similar to the one depicted in this image. Presently, I have partially implemented the chart with the code provided below. You can see it here. The code snippet I've developed so far is outlined as f ...

Warning in Google Script editor

Currently, I am working on creating some quick scripts to manipulate spreadsheets in my Google Drive. However, I am cautious about the script unintentionally running and making changes to data before I am ready or executing multiple times after completing ...

Displaying Dates in an Express Application using EJS

I have a MySQL table with a column containing date data. I am building a webpage to display this data in a more user-friendly way. Currently, the displayed result looks like this: I would like the dates in the column to be formatted as something like ...

Helping React and MUI components become mobile responsive - Seeking guidance to make it happen

My React component uses Material-UI (MUI) and I'm working on making it mobile responsive. Here's how it looks currently: But this is the look I want to achieve: Below is the code snippet for the component: import React from 'react'; i ...

What is the correct method for properly disposing of a Three.js Scene in version r55?

It appears that Three.js lacks a proper method for disposing of a THREE.Scene and all its contents. My current approach is as follows: $.each(scene.__objects, function(idx, obj) { scene.remove(obj); ...

Tips for dynamically updating an AngularJS table cell value from a database without needing to refresh the entire page

I have developed an application that utilizes xeditable to display a table populated with data from a mySQL database. The challenge I am currently facing involves the dynamic nature of the database table, as it constantly undergoes changes in the backgrou ...

The JSON data appears to be correct, yet it is not functioning properly when transmitted to X

I have a JSON object that has been validated using https://jsonlint.com/. However, I am encountering an error when trying to use this JSON with the Xero API as shown below. { "Type": "ACCREC", "Status": "AUTHORISED", "DueDate": "2021-12-11T14:24:0 ...