Trying to create a script that will show how a word changes through multiple translations using Google Translate, but struggling with Javascript. The problem I'm facing is hard to pinpoint:
function initialize() {
var word = "Hello";
var english = [word];
var german = [];
document.write("1");
var i = 0;
for (i=0; i<10; i++) {
google.language.translate(english[i], 'en', 'de', function(result) {
if (!result.error) {
german.push(result.translation);
document.write(result.translation);
}
else {
document.write(result.error.message);
}
document.write("2");
});
document.write("3");
google.language.translate(german[i], 'de', 'en', function(result) {
if (!result.error) {
english.push( result.translation );
document.write ( result.translation );
}
else {
document.write(result.error.message);
}
document.write("4");
});
document.write("5");
}
}
google.setOnLoadCallback(initialize);
The second translation call relies on the first one's result as an input. It should output text like this in the end:
1Hallo23Hello45Hallo23Hello45Hallo23Hello45 ...
However, it only displays 13Hallo2 and then crashes. The order of execution hints at asynchronous behavior. I am used to sequential code! Assistance needed - How can I ensure the loop waits for the first translation to finish before proceeding?