[JS]Loop hole

Joined
Aug 6, 2009
Messages
2,154
Reaction score
442
Code:
function GeolocateStopsTik()
{
	if (geoIndex < 50) // limit to array length in puture
	{
		GeolocateStopsTok(myStops[geoIndex]);
	}
}

function GeolocateStopsTok(stop)
{
	if (stop.marker == null)
	{
		geocoder.geocode( { 'address': stop.house + " " + stop.street + " " + stop.city + " " + stop.zip }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK)
			{
				stop.marker = new google.maps.Marker({
					map: map,
					position: results[0].geometry.location
				});
				geoIndex = geoIndex + 1;
				GeolocateStopsTik();
			}
			else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
			{
				setTimeout(GeolocateStopsTik(), 1000);
			}
			else
			{
				alert("Geocode was not successful for the following reason: " + status);
				//GeolocateStopsTik();
			}
		});
	}
}

Using tiktok principle here instead of loop.

Browser hangs and crashes when "setTimeout(GeolocateStopsTik(), 1000);" gets called.

The code geolocates address. If successful increase index and call Tik. If limit thrown, call tik with a delay, otherwise doesn't matter for now.

No idea what I am missing. Please do help :/:

Edit: never-mind still having a problem
 
Last edited:
Wow and it was that simple.

Thank you :thumbup:

It's actually simpler:
PHP:
setTimeout(GeolocateStopsTik, 1000)

What kutsumo suggested essentially does this:
PHP:
setTimeout(function() { function() {
    // internal function code

}}, 1000)

Another way to misuse setTimeout is to use the built-in eval feature it has:
PHP:
// eval is evil. This code is commented out because it is naughty.
// setTimeout("GeolocateStopsTik()", 1000)

Instead of calling the function and passing the return value, you want to pass the actual function as an argument. setTimeout() will later call the function you pass after 1000 milliseconds have passed. So don't use 'functionName()' (function call syntax), but instead use 'functionName' (variable name syntax).

You can also pass anonymous functions. For example, this would also work:
PHP:
setTimeout(
	  function()
	  {
		// limit to array length in puture
		if (geoIndex < 50)
		{
			GeolocateStopsTok(myStops[geoIndex]);
		}
	  }
	, 1000
)
All of this applies to setInterval(), too.

Note: The difference between an interval and a timeout is that an interval will execute your function every x milliseconds, while a timeout will only execute your function once after x milliseconds.​

Hope that clears it up.
 
Last edited:
Back