Excessive geolocation position responses in Angular 5

I am trying to implement an Angular 5 component that will continuously fetch my current location every 3 seconds if it has changed. Here is a snippet of my code:

export class WorkComponent implements OnInit {

 constructor(private userService: UserService) {}

 ngOnInit() {
    this.subscribeCurrentPosition();
  }

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  
          setInterval(() => this.subscribeCurrentPosition(), 3000);
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }
}

The issue I am facing is that the subscribeCurrentPosition() function is being called multiple times within the 3-second interval, resulting in redundant requests to the geolocation API and eventually triggering an alert for sending too many requests.

I have confirmed that there is only one instance of the component at any given time, so I am unsure why the function is being invoked more than once within the specified timeframe. Any insights or suggestions would be greatly appreciated.

Answer №1

The reason for the issue is the usage of setInterval. Each time you use setInterval, a new task is created that will repeat endlessly. When your function executes, it recursively calls sentInterval, leading to an accumulation of tasks over time. To resolve this, consider using setTimeout instead, as it will only execute once. Since there is a recursive mechanism in place, it will continue to be called each time a response is received:

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  //send position to backend
          setTimeout(() => this.subscribeCurrentPosition(), 3000);
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }

Alternatively, you can still utilize setInterval, but place it outside of your function:

  subscribeCurrentPosition() {
    if (window.navigator.geolocation) {
      window.navigator.geolocation.watchPosition(
        (position) => {
          this.myLocation = new TrackLocation(null, position.coords.latitude, position.coords.longitude);
          this.userService.sendCurrentPosition(this.myLocation, this.supplierId);  //send position to backend
        }, (error) => {
          LoggingService.error('Geolocation error: '+ error);
        });
      } else {
        LoggingService.error('Geolocation not supported in this browser');
      }
  }
  setInterval(() => this.subscribeCurrentPosition(), 3000);

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

display the hidden box contents when clicking the button within a PHP loop

I am attempting to create a simple e-commerce site for learning purposes, but I encountered an issue when trying to display information upon clicking a button. The button does not seem to trigger any action as expected. It is meant to reveal text from the ...

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

Clicking on the image does not result in a larger image being displayed

Currently working on an assignment that requires a modal pop-out to display larger versions of photos when clicked, with the option to go back using the X button. Unfortunately, I'm facing issues with the X button not functioning properly and images n ...

How can I incorporate a vertical line divider and a legend into a curved box using HTML and CSS?

https://i.sstatic.net/dj4zb.png I have this image that I need to divide into three sections with a legend at the top, similar to the image shown. So far, this is the code I have, but I'm struggling with creating the vertical line, adding space betwe ...

problem with saving session data

I am attempting to access data from another page using session storage. On my initial page, named home.html function go_to_faq(qnum){ window.open('FAQ.html', '_blank'); sessionStorage.setItem('key2', qnum); } <a s ...

How to select specific folders for packaging with asar within an Electron app

I'm currently working on an Electron application and experimenting with using asar to package the node_modules and sources directories, while excluding other directories. However, I've run into an issue where when building the application with a ...

How to Save Checkbox Selections in the Order They Were Clicked Using PHP

I have a form with 4 checkboxes, and I need to save the selected checkboxes in the database in the order they are clicked. For example, if the checkboxes are clicked in the sequence 1, 3, 4, 2, then they should be saved in the database in that exact order. ...

Injecting Dependencies Into ExpressJS Routes Middleware

Hey there! I'm currently working on injecting some dependencies into an expressjs route middleware. Usually, in your main application, you would typically do something like this: const express = require('express'); const userRouter = requi ...

What is the reason behind "readFile" consuming more memory than the actual length of the file being read?

I am facing an issue with memory consumption when handling a large number of log files in a directory containing around 300,000 files. It seems that there is a memory leak when I use the "readFile" method to read all these files. Below is an example of No ...

Is there a way to obtain the current URL within the index.html file using Vue.js?

How can I retrieve the current URL in my index.html file using Vue.js? When using pure JavaScript in index.html, I am only able to obtain the URL of the initial page. In order to capture the URL of other pages, I need to refresh the page as the value of ...

Is there a glitch in the three.js loadOBJMTL loader?

Encountering an issue with the OBJMTL loader in three.js. I'm working with obj/mtl/jpeg files and getting load errors that look like this: "THREE.OBJMTLLoader: Unhandled line 4033/5601/6659" OBJMTLLoader.js:347 Seems like there is a problem with a c ...

Upon submission in Vue, the data variable becomes undefined

I set isError to false in the data, but when there is an error from Laravel, I receive a 422 error. I want to then set isError to true, but when I do, I get an error in the console saying that isError is undefined even though it has been defined. What coul ...

Retrieving a parameter in NextJS from the request.body when it is not found

In the API code for my nextJS, I have implemented the following logic: export default async function handler(request, response) { if (request.method === "POST") { const type = request.body.type ?? 'body type' const ...

Using TypeScript to specify the return type of a non-mutating extension function from an external module

Imagine utilizing an external package named "foo". This package's primary export is an object containing an .extend() method that enables functionality addition by generating a derived object (while leaving the original untouched). The process typical ...

Improving the functionality of multiple range slider inputs in JavaScript codeLet me

Is it possible to have multiple range sliders on the same page? Currently, all inputs only affect the first output on the page. Check out an example here: http://codepen.io/andreruffert/pen/jEOOYN $(function() { var output = document.querySelectorAl ...

Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript. View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview However, when the button is clicked, the ...

We are in need of a provider for the Ionic Network native plugin

I have encountered an issue while trying to use Ionics native plugin "Network" as it fails due to a missing provider. To prevent any errors, I performed a fresh installation of Ionic along with the necessary dependencies: ionic cordova plugin add cordova- ...

Angular eliminates the use of directories in the URL during the routing process

I recently configured a local IIS and set up an application within a directory named test: When I accessed the URL in my browser: "http://localhost/test" The route for this scenario is defined as follows: const routes: Routes = [ { path: '&apos ...

What is the process for transforming an AJAX request's onreadystatechange into a promise?

During the process of making a javascript AJAX request, I initially utilized the traditional callback approach to call the callback function within the onreadystatechange and retrieve all the values of readyState. However, upon switching my callback funct ...

angular table disabled based on condition

I have a table in my HTML file and I am trying to figure out how to disable the onClick function if the start date is greater than the current date. <ng-container matColumnDef="d"> <th mat-header-cell ...