1

I'm trying to execute the following JavaScript code, but I'm getting error.

var services = [{place_id:'okkkkkk'}];
var delay = 100;
var nextAddress = 0;

function theNext() {
  if (nextAddress < services.length) {
    setTimeout('getDetails("' + services[nextAddress].place_id + '", theNext)', delay);
    nextAddress++;
  } else {

  }
}


function getDetails(address, next) {
  alert('ok');
}


theNext();

Errror:

VM687:1 Uncaught ReferenceError: getDetails is not defined

The function is defined and I'm not sure whats causing the problem:

https://jsfiddle.net/qmnaykqw/

user1012181
  • 8,648
  • 10
  • 64
  • 106

1 Answers1

3

When you pass a string to setTimeout it gets evaluated in the global scope. Since getDetails is defined in another function (on your JSFiddle link at least) which is called onload, it is out of scope when the string is evaluated.

You need to pass a function to setTimeout instead. That will create a closure and preserve the scope.

function delayed_function() {
    getDetails(services[nextAddress].place_id, theNext);
}

setTimeout(delayed_function, delay);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Can you look at the script here: http://acleach.me.uk/gmaps/v3/plotaddresses.htm It looks like that guy made it work :/ – user1012181 Mar 31 '16 at 18:04
  • @user1012181 — Unlike your JSFiddle version, that code doesn't wrap the code in another function which gets assigned as a load event handler. – Quentin Mar 31 '16 at 18:05
  • Sorry, I didn't get it. Can you explain with that bit of code? :/ – user1012181 Mar 31 '16 at 18:07
  • @user1012181 — What don't you understand? The answer has a paragraph explaining what the problem is, a paragraph explaining the solution, and then a drop in replacement for the broken code. – Quentin Mar 31 '16 at 18:08
  • Yes I understand what you have given in the answer section. But if you check the link I provided, that guy is passing the function as a string. – user1012181 Mar 31 '16 at 18:09
  • 1
    @user1012181 — And on that page `getDetails` is a global. On your JSFiddle it is scoped to the onload event handler function. – Quentin Mar 31 '16 at 18:10
  • Even in this case, the nextAddress++; is happening soon. – user1012181 Mar 31 '16 at 19:48
  • @user1012181 — Then have its initial value be one lower. – Quentin Mar 31 '16 at 19:55