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);
});
}