0

please help with getting a right function or method to stop the setTimeout function.

I've been trying with the following codes but the setTimeout "loop" could not be stopped. What i'm trying to do is to get the user's current location every 5 seconds, and then when i press the stop button. It stops getting the location.

   function geoTrackstart(){  
//geolocation code
}); 
 timer = setTimeout(geoTrackstart, 5000);
}

function geoTrackstop(){
  clearTimeout(geoTrackstart);
            timer = 0;
}
August
  • 12,410
  • 3
  • 35
  • 51

2 Answers2

1

I think you want to use like this:

function geoTrackstart(){  
   //geolocation code
}); 
timer = setTimeout(geoTrackstart, 5000);//set timer

function geoTrackstop(){
  clearTimeout(timer);//clear the timer
  //setTimeout(geoTrackstart,5000);//set timeout if you want to run again
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

If you're polling for the geo i'd use a interval rather than a timeout so that it's run every 5 seconds until you stop it, this way you don't have to create a new timeout every 5 seconds -- unless you wanted to create the timeouts manually.:

var geoFetchInterval;
function geoTrackstart(); {};

//if you want it to run immediately the first time
geoTrackStart(); 

//start the interval
geoFetchInterval = setInterval(geoTrackStart, 5000);

function getTrackStop() {
  clearInterval(geoFetchInterval);
};

//assuming jquery
$('#stop-button').on('click', getTrackStop);
Brodie
  • 8,399
  • 8
  • 35
  • 55