Development Javascript freezes browser... what am I doing wrong?

Discussion in 'Software' started by thecrownles, 12 Sep 2008.

  1. thecrownles

    thecrownles What's a Relix?

    Joined:
    27 Feb 2004
    Posts:
    733
    Likes Received:
    0
    So I'm working on this javascript code that uses Google's language API to translate my page without a reload and without me typing up separate translations for each page, but the script freezes when it is executed. When I add an alert to the code that is being looped, it slows it down and for some reason will translate my page correctly, but when I remove the alert and let it run full speed, Firefox or Chrome crashes (two browsers I have tested on so far). I suspect this has something to do with the browser having too many function calls and thinking there is a memory leak or something.

    Code:
    <!--
    var src="en";
    
    function translateTo(dst){
    	alert("debug1");
    	allEl = document.getElementsByTagName("*");
    	var classExp = new RegExp("(^|\\s)" + "noTranslate" + "(\\s|$)");
    	var whitespace = new RegExp("^\\s*$");
    	for(i=0;i<allEl.length;i++){
    		if(!classExp.test(allEl[i].className) && allEl[i].nodeName!="SCRIPT"){
    			for(j=0;j<allEl[i].childNodes.length;j++){
    				if(allEl[i].childNodes[j].nodeType==3 && !whitespace.test(allEl[i].childNodes[j].nodeValue)){
    					variable = translateChunk(allEl[i].childNodes[j].nodeValue,src,dst,allEl[i].childNodes[j]);
    					}
    				}
    			}
    		}
    	src = dst;
    	}
    
    function translateChunk(text,src,dst,node){
    	google.language.translate(text,src,dst,function(result){
    		if(!result.error)
    			node.nodeValue=result.translation;
    		else
    			alert(result.error.message);
    			});
    //	alert("wait");   *************When uncommented, the script works
    	return(0);
    	}
    	
    -->
    
    Here is a link to a page that does a similar thing, but with much simpler code for some reason.

    So I'm open to any comments- other ways of doing this, or if it would be easier to just give up and write separate language versions of the page. It's just confusing me why it works with the alert, but crashes the browser otherwise.
     
  2. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    Long shot (after a REALLY quick glance through your code and the code you linked to):
    Google Language API accepts 500 characters per request
    so maybe your strings are too long? Wouldn't really explain why it works with the alert, though, except maybe because of the amount of data being returned too slowly, and the browser waiting for a response...
     

Share This Page