views:

160

answers:

1

Hello, I am developing a simple web app that uses the Google translation API in order to translate a text into different languages and then back to the first one.

The problem is that when I call google.language.translate(...) a callback function is specified which updates a textarea in my page. Here:

while (i < translationNumber) {
  google.language.translate(testua, languages[i] , languages[i+1],
  function(result) {
    if (result.translation) {
      text = result.translation;
      f.textarea1.value = text;
    }
  });

  alert('You must not close this until translation is done');
  i++;
}

As you see, an alert is needed in order to manually wait for the translation to end so it is correctly translated in the order of my languages array, otherwise múltiple translate calls are pending and the order breaks. It would be great if I could use some kind of semaphore as in java or C, however I am quite newbie in Javascript and I don't know how could this be done.

+8  A: 

You could instead make this a function which will call itself on completion

function translate(i) {
  google.language.translate(testua, languages[i], languages[i+1], function(result) {
    if (result.translation) {
      text = result.translation;
      f.textarea1.value = text;
      if (i < translationNumber) { translate(i++); }
    }
  }
}

That way, the next translation will only be instansiated after callback from translation.

edit: The only thing you need to add is a check, to see if i has reached the desired value, so it doesn't go on for ever (:

peirix
To infinity, and beyond!
Blixt
Thanks, I think that will work :-)
Hiperi0n