2

I have implemented a timer which sends GPS coordinates to a server every 5 seconds and should stop doing so once the stop button is pressed. The problem is that the timer runs one last time after pressing the stop button which means that the timer is not terminated immediately. I could not find any solution to stop the timer immediately. Which is surprsiing for me as i assumed it to be a common issue. May be there is something i am doing wrong. I implemented the timer from here.

My code

$(document).on('click', '#sendCoordinates', sendCoordinates);
$(document).on('click', '#stopSending', stopSending);
function sendCoordinates() {
   app.sendIntervalId = setInterval(turnGpsOnAndSend,5000);
}
function stopSending() {
   console.log("Trip ended");
   clearInterval(app.sendIntervalId);
}
function turnGpsOnAndSend() {
   if (navigator.geolovation) {
      navigator.geolocation.getCurrentPosition(function(position){
         var lat = position.coords.latitude;
         var lng = position.coords.longitude;
         var data = {
            lat: lat,
            lng: lng
         };
         sendCoordinatesToServer(data);
      },function (error) {
         console.log("GPS error");
      }
      )
   }
}
function sendCoordinatesToServer(data){
   var payLoad = data;
   var invocation = $.ajax({
      type: "PUT",
      url: app.url,
      contentType: 'application/json',
      data: payLoad
   }).done(function(response) {
         console.log("success");
   }).fail(function(jqXHR,textStatus,errorThrown) {
         console.log("fail" + jqXHR.status);
   });
}
Community
  • 1
  • 1
Arsalan Ahmed
  • 383
  • 2
  • 3
  • 14
  • are you sure it's not just a timing issue between clicking the button and the function executing? Why not put your clearInterval() in the click listener and see if that stops it immediately. – Cruiser Oct 18 '16 at 13:16
  • @Cruiser The `clearInterval` _is_ in the click listener. – James Thorpe Oct 18 '16 at 13:17
  • no, he's calling another function in the listener that then calls clearInterval – Cruiser Oct 18 '16 at 13:18
  • @Cruiser The click event is being bound directly to `stopSending`, which is calling `clearInterval`. There is no intermediate function. – James Thorpe Oct 18 '16 at 13:20
  • my point is to bind clearInterval to it directly so it the function doesn't run a console.log before clearInterval, because i think it's a timing issue with when the button is clicked and when clearInterval is actually executed – Cruiser Oct 18 '16 at 13:22
  • @Cruiser How are you going to bind `clearInterval` directly to the event without a wrapper function to pass the interval ID parameter? Either way, all the code is synchronous - once the click event has started, the interval will be cleared before the timer fires again. – James Thorpe Oct 18 '16 at 13:24
  • i have an ajax call and a GPS function. sorry for not giving the whole code earlier. I have updated the code – Arsalan Ahmed Oct 18 '16 at 13:46
  • 1
    @Arsalan Can you explain why you think it's running one more time? Is it perhaps because you see `success` being logged once more after `Trip ended`? That's to be expected if you click stop after that request has been initiated, since you're doing an async `PUT` to the server. – James Thorpe Oct 18 '16 at 13:47
  • 2
    I believe `getCurrentPosition` is also async, so there's another potential source of things getting out of order too. – James Thorpe Oct 18 '16 at 13:49
  • @JamesThorpe you are correct. I increased the timer reset value to 15 secs to see whats happening. It takes around 3-5 secs for my phone to get the GPS coordinates. So with the 5 sec timer whenever i was pressing stop i was already inside `turnGpsOnAndSend` function. So it always sends one extra trip. With 15 secs value it did not happen. – Arsalan Ahmed Oct 18 '16 at 14:05
  • @JamesThorpe one more question. I am not well familarized with async functions. I might have many other things or interactions happening in the app like location update on a map, and moving between different pages and other async ftns while this `sendCoordinates` is running: I would like it to run as a seperate process or thread not affecting other functionalties. Will this piece of code do that or i need to take another approach. I am working on a cordova application. thanks – Arsalan Ahmed Oct 18 '16 at 14:20

0 Answers0