0

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.

2
  • Do you want the textarea being updated according to the array order? Commented Jul 16, 2009 at 7:47
  • I want to remove that alert and make the google translate function call blocking or synchronous, in order to the translation to be done secuentially, otherwise it executes the loop and I then receive the translations but not sequential ones, just translations of the original text into different languages. Commented Jul 16, 2009 at 7:55

1 Answer 1

8

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 (:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.