javascript - Failed to load source for: http://localhost/js/m.js - javascript

Why oh why oh why... I can't figure out why I keep getting this error. I think I might cry.
/*** common functions */
function GE(id) { return document.getElementById(id); }
function changePage(newLoc) {
nextPage = newLoc.options[newLoc.selectedIndex].value
if (nextPage != "")
{
document.location.href = nextPage
}
}
function isHorizO(){
if (navigator.userAgent.indexOf('iPod')>-1)
return (window.orientation == 90 || window.orientation==-90)? 1 : 0;
else return 1;
}
function ShowHideE(el, act){
if (GE(el)) GE(el).style.display = act;
}
function KeepTop(){
window.scrollTo(0, 1);
}
/* end of common function */
var f = window.onload;
if (typeof f == 'function'){
window.onload = function() {
f();
init();
}
}else window.onload = init;
function init(){
if (GE('frontpage')) init_FP();
else {
if (GE('image')) init_Image();
setTimeout('window.scrollTo(0, 1)', 100);
}
AddExtLink();
}
function AddExtLink(){
var z = GE('extLink');
if (z){
z = z.getElementsByTagName('a');
if (z.length>0){
z = z[0];
var e_name = z.innerHTML;
var e_link = z.href;
var newOption, oSe;
if (GE('PSel')) oSe = new Array(GE('PSel'));
else
oSe = getObjectsByClassName('PSel', 'select')
for(i=0; i<oSe.length; i++){
newOption = new Option(e_name, e_link);
oSe[i].options[oSe[i].options.length] = newOption;
}
}
}
}
/* fp */
function FP_OrientChanged() {
init_FP();
}
function init_FP() {
// GE('orientMsg').style.visibility = (!isHorizO())? 'visible' : 'hidden';
}
/* gallery */
function GAL_OrientChanged(link){
if (!isHorizO()){
ShowHideE('vertCover', 'block');
GoG(link);
}
setTimeout('window.scrollTo(0, 1)', 500);
}
function init_Portfolio() {
// if (!isHorizO())
// ShowHideE('vertCover', 'block');
}
function ShowPortfolios(){
if (isHorizO()) ShowHideE('vertCover', 'none');
}
var CurPos_G = 1
function MoveG(dir) {
MoveItem('G',CurPos_G, dir);
}
/* image */
function init_Image(){
// check for alone vertical images
PlaceAloneVertImages();
}
function Img_OrtChanged(){
//CompareOrientation(arImgOrt[CurPos_I]);
//setTimeout('window.scrollTo(0, 1)', 500);
}
var CurPos_I = 1
function MoveI(dir) {
CompareOrientation(arImgOrt[CurPos_I+dir]);
MoveItem('I',CurPos_I, dir);
}
var arImgOrt = new Array(); // orientation: 1-horizontal, 0-vertical
var aModeName = new Array('Horizontal' , 'Vertical');
var arHs = new Array();
function getDims(obj, ind){
var arT = new Array(2);
arT[0] = obj.height;
arT[1] = obj.width;
//arWs[ind-1] = arT;
arHs[ind] = arT[0];
//**** (arT[0] > arT[1]) = (vertical image=0)
arImgOrt[ind] = (arT[0] > arT[1])? 0 : 1;
// todor debug
if(DebugMode) {
//alert("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal'))
writeLog("["+obj.width+","+obj.height+"] mode="+((arT[0] > arT[1])? 'verical' : 'hoziontal')+' src='+obj.src)
}
if (arImgOrt[ind]) {
GE('mi'+ind).className = 'mImageH';
}
}
function CompareOrientation(imgOrt){
var iPhoneOrt = aModeName[isHorizO()];
GE('omode').innerHTML = iPhoneOrt;
//alert(imgOrt == isHorizO())
var sSH = (imgOrt == isHorizO())? 'none' : 'block';
ShowHideE('vertCover', sSH);
var sL = imgOrt? 'H' : 'V';
if (GE('navig')) GE('navig').className = 'navig'+ sL ;
if (GE('mainimage')) GE('mainimage').className = 'mainimage'+sL;
var sPfL = imgOrt? 'Port-<br>folios' : 'Portfolios' ;
if (GE('PortLnk')) GE('PortLnk').innerHTML = sPfL;
}
function SetGetDim( iMInd){
var dv = GE('IImg'+iMInd);
if (dv) {
var arI = dv.getElementsByTagName('img');
if (arI.length>0){
var oImg = arI[0];
oImg.id = 'Img'+iMInd;
oImg.className = 'imageStyle';
//YAHOO.util.Event.removeListener('Img'+iMInd,'load');
YAHOO.util.Event.on('Img'+iMInd, 'load', function(){GetDims(oImg,iMInd);}, true, true);
//oImg.addEventListener('load',GetDims(oImg,iMInd),true);
}
}
}
var occ = new Array();
function PlaceAloneVertImages(){
var iBLim, iELim;
iBLim = 0;
iELim = arImgOrt.length;
occ[0] = true;
//occ[iELim]=true;
for (i=1; i<iELim; i++){
if ( arImgOrt[i]){//horizontal image
occ[i]=true;
continue;
}else { // current is vertical
if (!occ[i-1]){//previous is free-alone. this happens only the first time width i=1
occ[i] = true;
continue;
}else {
if (i+1 == iELim){//this is the last image, it is alone and vertical
GE('mi'+i).className = 'mImageV_a'; //***** expand the image container
}else {
if ( arImgOrt[i+1] ){
GE('mi'+i).className = 'mImageV_a';//*****expland image container
occ[i] = true;
occ[i+1] = true;
i++;
continue;
}else { // second vertical image
occ[i] = true;
occ[i+1] = true;
if (arHs[i]>arHs[i+1]) GE('mi'+(i+1)).style.height = arHs[i]+'px';
i++;
continue;
}
}
}
}
}
//arImgOrt
}
function AdjustWebSiteTitle(){
//if (GE('wstitle')) if (GE('wstitle').offsetWidth > GE('wsholder').offsetWidth) {
if (GE('wstitle')) if (GE('wstitle').offsetWidth > 325) {
ShowHideE('dots1','block');
ShowHideE('dots2','block');
}
}
function getObjectsByClassName(className, eLTag, parent){
var oParent;
var arr = new Array();
if (parent) oParent = GE(parent); else oParent=document;
var elems = oParent.getElementsByTagName(eLTag);
for(var i = 0; i < elems.length; i++)
{
var elem = elems[i];
var cls = elem.className
if(cls == className){
arr[arr.length] = elem;
}
}
return arr;
}
////////////////////////////////
///
// todor debug
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
var sRet = ""
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
sRet = pair[1];
}
}
return sRet
//alert('Query Variable ' + variable + ' not found');
}
var oLogDiv=''
function writeLog(sMes){
if(!oLogDiv) oLogDiv=document.getElementById('oLogDiv')
if(!oLogDiv) {
oLogDiv = document.createElement("div");
oLogDiv.style.border="1px solid red"
var o = document.getElementsByTagName("body")
if(o.length>0) {
o[0].appendChild(oLogDiv)
}
}
if(oLogDiv) {
oLogDiv.innerHTML = sMes+"<br>"+oLogDiv.innerHTML
}
}

First, Firebug is your friend, get used to it. Second, if you paste each function and some supporting lines, one by one, you will eventually get to the following.
var DebugMode = (getQueryVariable("debug")=="1")
function getQueryVariable(variable)
You can't execute getQueryVariable before it is defined, you can create a handle to a future reference though, there is a difference.
There are several other potential issues in your code, but putting the var DebugMode line after the close of the getQueryVariable method should work fine.

It would help if you gave more context. For example, is
Failed to load source for:
http://localhost/js/m.js
the literal text of an error message? Where and when do you see it?
Also, does that code represent the contents of http://localhost/js/m.js? It seems that way, but it's hard to tell.
In any case, the JavaScript that you've shown has quite a few statements that are missing their semicolons. There may be other syntax errors as well. If you can't find them on your own, you might find tools such as jslint to be helpful.

make sure the type attribute in tag is "text/javascript" not "script/javascript".

I know it is more than a year since this question was asked, but I faced this today. I had a
<script type="text/javascript" src="/test/test-script.js"/>
and I was getting the 'Failed to load source for: http://localhost/test/test-script.js' error in Firebug. Even chrome was no loading this script. Then I modified the above line as
<script type="text/javascript" src="/test/test-script.js"></script>
and it started working both in Firefox and chrome. Documenting this here hoping that this will help someone. Btw, I dont know why the later works where as the previous one didn't.

Related

In Javascript function onLoadPopulate() is not working?

function onLoadPopulate() {
var grid = $("#grid0");
var numberOfRecords = grid.getGridParam("records");
var dataFromGrid = grid.jqGrid('getGridParam', 'data');
var count=0;
var link;
if(numberOfRecords>0){
numberOfRecords=endNo;
count=begNo-1;
}
for ( ; count < numberOfRecords; count++) {
var program = dataFromGrid[count].program;
var programVal="";
var programs = program.replace(/\s/g,'').split(',');
for ( var i = 0; i< programs.length;i++) {
if (programs[i] == "FS") {
if (programVal == "") {
programVal = 'DOG';
} else {
programVal = programVal.concat(",DOG");
}
} else if (programs[i] == "TF") {
console.log("in TF");
if (programVal == "") {
programVal = 'CAT';
} else {
programVal = programVal.concat(",CAT");
}
}
grid.jqGrid('setCell', count + 1, 'program',
programVal);
}
}
TEST DATA:
program = FS, TF
result i'm getting : DOG but
the result i need : DOG,CAT
When it is doing else if Even if programs[i] = TF it is skipping if loop inside.
Can anyone help with this JavaScript function?
I can't figure it out what is wrong.
issue with input data consisted of special characters i used following replace and it worked
.replace(/[^a-z0-9,\s]/gi,'').replace(/[_\s]/g,'').split(',')

auto scrolling to find in page hilighted word

I have put this script on my every html page:
with this css:
strong.searchword {
background-color: #e8d850;
font-weight:normal;
}
My highlight.js code is:
function DocSearch() {
this.highlightWord = function(node,word) {
// Iterate into this nodes childNodes
if (node.hasChildNodes) {
var hi_cn;
for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
this.highlightWord(node.childNodes[hi_cn],word);
}
}
// And do this node itself
if (node.nodeType == 3) { // text node
tempNodeVal = node.nodeValue.toLowerCase();
tempWordVal = word.toLowerCase();
if (tempNodeVal.indexOf(tempWordVal) != -1) {
pn = node.parentNode;
// check if we're inside a "nosearchhi" zone
checkn = pn;
while (checkn.nodeType != 9 &&
checkn.nodeName.toLowerCase() != 'body') {
// 9 = top of doc
if (checkn.className.match(/\bnosearchhi\b/)) { return; }
checkn = checkn.parentNode;
}
if (pn.className != "searchword") {
// word has not already been highlighted!
nv = node.nodeValue;
ni = tempNodeVal.indexOf(tempWordVal);
// Create a load of replacement nodes
before = document.createTextNode(nv.substr(0,ni));
docWordVal = nv.substr(ni,word.length);
after = document.createTextNode(nv.substr(ni+word.length));
hiwordtext = document.createTextNode(docWordVal);
hiword = document.createElement("strong");
hiword.className = "searchword";
hiword.appendChild(hiwordtext);
pn.insertBefore(before,node);
pn.insertBefore(hiword,node);
pn.insertBefore(after,node);
pn.removeChild(node);
}
}
}
}
}
var DOMContentLoaded = false;
function addContentLoadListener (func) {
if (document.addEventListener) {
var DOMContentLoadFunction = function () {
window.DOMContentLoaded = true;
func();
};
document.addEventListener("DOMContentLoaded", DOMContentLoadFunction, false);
}
var oldfunc = (window.onload || new Function());
window.onload = function () {
if (!window.DOMContentLoaded) {
oldfunc();
func();
}
};
}
addContentLoadListener( function() {
var q = window.location.search.substring(1).split('&');
if(!q.length)
return false;
var docSearch = new DocSearch();
var bodyEl = document.body;
for(var i=0; i<q.length; i++){
var vars = q[i].split('=');
new DocSearch().highlightWord(bodyEl,decodeURIComponent(vars[1]));
}
});
/*
window.onload = function() {
var q = window.location.search.substring(1).split('&');
if(!q.length)
return false;
var docSearch = new DocSearch();
var bodyEl = document.body;
for(var i=0; i<q.length; i++){
var vars = q[i].split('=');
new DocSearch().highlightWord(bodyEl,decodeURIComponent(vars[1]));
}
}
With this url mypage.html?suchwort=rose
I got word rose highlighted.
What I am having trouble with is then automatically scrolling to the highlighted word.
Is there any way to do this with javascript/jQuery?

Javascript: scope effect despite order of execution

Please note: This is not a question about scope, per se. I understand that in order to make the code work, I should make a deep copy of the variable board rather than assigning var tboard = board. However, I am not clear why making a shallow copy has the effect I describe below.
I am experiencing something I find baffling. Basically, a global variable (board) gets altered and I have no clue how. board is initialized in the function NewGame() (which is called from select()) as an empty array. After it is initialized, nothing else is called until the user clicks a square on the board (assuming the user has selected Xs for simplicity). When that happens, the function playerMove() is called. The baffling thing is that console.log(board) at the top of playerMove() prints out an array that has an x is the clicked position and os everywhere else (ie not empty). This is bizarre because the board is empty at the end of select() (which called NewGame()) and nothing else should happen in between. To demonstrate this, I print out the function name at the top of each function and I print out the board variable in the select() function and playerMove() function to show that it changes despite nothing else being called. Please note that to get this behavior, refresh the page (otherwise the board variable starts out full of os). I think this must be somewhat an issue of scope (because I am not making a deep copy of board) but it's strange because I have no clue what is being called that is changing the variable before it gets printed out at the top of playerMove().
Here is the link to my pen and the code: http://codepen.io/joshlevy89/pen/MKjxop?editors=101
$(document).ready(function() {
var pSym; // player's symbol
var cSym; // computer's symbol
var board;
var whosMove; // can be "player" or "computer" or "neither"
var gameOver;
setup();
$("#newgame").on('click', '#X', select);
$("#newgame").on('click', '#O', select);
$("#restart").on('click', setup);
$("table").on('click', 'td', playerMove);
function playerMove()
{
console.log('playerMove');
console.log(board);
if (whosMove === "player")
{
var val = $(this).data('value');
$('#g' + val).text(pSym);
var arr = PositionToCoords(val);
board[arr[0]][arr[1]] = pSym;
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0)
{
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "computer";
computerMove();
}
}
function computerMove() {
console.log('computerMove');
//var p1 = Math.floor(Math.random() * 3);
//var p2 = Math.floor(Math.random() * 3);
var tboard = board;
var pos = chooseMove(tboard);
var arr = PositionToCoords(pos);
board[arr[0]][arr[1]] = cSym;
DrawPosition(arr[0], arr[1], cSym);
var tboard = board;
var gc = gameCheck(tboard);
if (gc>=0) {
endGame(gc);
setTimeout(function(){setup();}, 1000);
return;
}
whosMove = "player";
}
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves=[];
var scores = [];
for (var i=1;i<10;i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}
function endGame(gc) {
console.log('endGame');
var str;
if (gc===1) { // somebody won
if (whosMove==="player"){
str = "You Won!"
}
else {
str = "You Lost :(";
}
}
else if (gc === 0){//draw
str = "It's a draw."
}
html = '<div id="closer">' + str + '</div>';
$('#endgame').html(html);
}
function gameCheck(tboard) {
console.log('gameCheck');
// get symbol to check for
var sym;
if (whosMove === "player") {
sym = pSym;
} else {
sym = cSym;
}
// check if in a row
var hrow;
var vrow;
// check for horizonal row
for (var i = 0; i < 3; i++) {
hrow = true;
vrow = true;
for (var j = 0; j < 3; j++) {
if (tboard[i][j] !== sym) {
hrow = false;
}
if (tboard[j][i] !== sym) {
vrow = false;
}
}
if ((hrow) || (vrow)) {
return 1;
}
}
var fdrow = true;
var bdrow = true;
for (var i = 0; i < 3; i++) {
if (tboard[i][i] !== sym) {
fdrow = false;
}
if (tboard[i][2 - i] !== sym) {
bdrow = false;
}
}
if ((fdrow) || (bdrow)) {
return 1;
}
// otherwise, check if board is full
var full = true;
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (tboard[arr[0]][arr[1]] === undefined) {
full = false;
break;
}
}
if (full === true) {
return 0;
}
// if neither 0 (tie) or win (1), return -1 (game not over)
return -1;
}
function select() {
console.log('select');
pSym = $(this).data('value');
$('#newgame').html('');
NewGame();
console.log(board);
}
function setup() {
console.log('select');
$('#endgame').html('');
html = '<div id="opener">Xs or Os? <div id="buttons">';
html += '<div id="X" data-value="X" class="btn btn-default">Xs</div>';
html += '<div id="O" data-value="O" class="btn btn-default">Os</div>';
html += '</div></div>';
$('#newgame').html(html);
}
function NewGame() {
console.log('NewGame');
$('td').empty();
board = new Array(3);
for (i = 0; i < 3; i++) {
board[i] = new Array(3)
};
if (pSym === "X") {
cSym = "O";
whosMove = "player";
} else {
cSym = "X";
whosMove = "computer";
computerMove();
}
}
function DrawPosition(p1, p2, sym) {
console.log('DrawPosition');
var pos = p1 * 3 + (p2 + 1);
$("#g" + pos).text(sym)
}
function PositionToCoords(pos) {
console.log('PositionToCoords');
var p1 = Math.ceil(pos / 3) - 1;
var p2 = ((pos - 1) % 3);
var arr = [p1, p2];
return arr;
}
});
Thanks in advance.
Simply add the break in the for loop fixes the problem. Am I missing anything?
function chooseMove(inboard) {
console.log('chooseMove');
// get the possible moves
var moves = [];
var scores = [];
for (var i = 1; i < 10; i++) {
var arr = PositionToCoords(i);
if (inboard[arr[0]][arr[1]] === undefined) {
moves.push(i);
var tboard = inboard;
tboard[arr[0]][arr[1]] = cSym;
var gc = gameCheck(tboard);
scores.push(gc);
break; // <<<<<<<<<<<< This break guarantees that the computer only makes one move
}
}
//console.log(moves);
//console.log(scores);
return moves[0]; // TEMPORARY
}

Load gif image > execute statement > hide gif

Is there something wrong with this sequence?
//loading_image is hidden at first
$('#run_only').click(function(e) {
$('#loading_image').show();
var def_main = false,
def_header = false,
def_iostream = false,
def_conio = false,
def_stdio = false,
def_math = false,
def_string = false;
//REMOVE PREVIOUSLY ADDED CLASSESS TO LN
$('#board_ln').contents().removeClass('line-error');
if(er_syntax_pre) {
var error_text = '<p>Syntax Error. Detected brace matching error.</p>';
var debugging_text = '<p>DEBUGGING: Check the proper pairing of ( ), { }, [ ], \' \', " " </p>';
mb_error(error_text, debugging_text);
} else {
mb_noerror('');//transfer this at the end part later
var inlineDiv_num = $('#board_code > div ').size(),
kword_search_raw="",
kword_search="",
kwordSyntaxSearch_tilde="",
kwordSyntaxSearch="",
noKeyword = true
er_text = new Array(),
er_ln = new Array(),
er_debug_text = new Array();
er_text = [];
er_ln = [];
er_debug_text = [];
for( var x=0; x<inlineDiv_num; x++ ) {
var inlineDiv_num_textL = $('#board_code > div ').eq(x).text().length,
inlineDiv_num_text = $('#board_code > div ').eq(x).text();
for( var y=0; y<inlineDiv_num_textL; y++) {
//kword_search = kword_search + inlineDiv_num_text.charAt(y);
kword_search_raw = kword_search_raw + inlineDiv_num_text.charAt(y);
kword_search = kword_search + inlineDiv_num_text.charAt(y);
//SEARCH FOR STRINGS AND REPLACE THEM
if(/(?:'[^']+'|"[^"]+")$/.test(kword_search)) {
//alert('found 2nd occurence of quote');
kword_search = kword_search.replace(/(?:'[^']+'|"[^"]+")$/, "!string!");
}
//alert(kword_search);
//include***********
if(/\s*\#include$/.test(kword_search) ) {
noKeyword = false;
//alert('at the tail of #include');
var kwordSyntaxSearch = sliceToEndString(x,y);
//alert('kwordSyntaxSearch: '+kwordSyntaxSearch);
//SYNTAX CHECKER
if( /^\s*<\s*iostream\.h\s*>*/.test(kwordSyntaxSearch) ) {
def_iostream = true;
var charLast = kwordSyntaxSearch.indexOf(">");
kwordSyntaxSearch_tilde = kwordSyntaxSearch.splice(charLast+1, 0, "~~");
} else if( /^\s*<\s*conio\.h\s*>*/.test(kwordSyntaxSearch) ) {
def_conio = true;
var charLast = kwordSyntaxSearch.indexOf(">");
kwordSyntaxSearch_tilde = kwordSyntaxSearch.splice(charLast+1, 0, "~~");
} else if( /^\s*<\s*stdio\.h\s*>*/.test(kwordSyntaxSearch) ) {
def_stdio = true;
var charLast = kwordSyntaxSearch.indexOf(">");
kwordSyntaxSearch_tilde = kwordSyntaxSearch.splice(charLast+1, 0, "~~");
} else if( /^\s*<\s*string\.h\s*>*/.test(kwordSyntaxSearch) ) {
def_string = true;
var charLast = kwordSyntaxSearch.indexOf(">");
kwordSyntaxSearch_tilde = kwordSyntaxSearch.splice(charLast+1, 0, "~~");
} else if( /^\s*<\s*math\.h\s*>*/.test(kwordSyntaxSearch) ) {
def_math = true;
var charLast = kwordSyntaxSearch.indexOf(">");
kwordSyntaxSearch_tilde = kwordSyntaxSearch.splice(charLast+1, 0, "~~");
} else {
//alert('#include syntax error');
er_text.push('Error: Syntax | Runtime. #include<headerfile.h>');
er_debug_text.push('Debugging: (1)Check text after "#include" (2)Check "support" for supported libraries');
er_ln.push(x);
y=inlineDiv_num_textL;
x=inlineDiv_num;
}//else
}//IF FOUND #INCLUDE|
}//for y
}//for x
//NO KEYWORDS AT ALL
if(noKeyword){
er_text[0] = "Error: No keywords detected";
er_debug_text[0] = "Debugging: Make sure that you are using the supported C++ keywords of this system";
er_ln[0] = inlineDiv_num-1;
mb_error(er_text[0], er_debug_text[0], er_ln[0]);
}
if(er_ln.length > 0) {
mb_error(er_text[0], er_debug_text[0], er_ln[0]);
}
}//else no brace error
$('#loading_image').hide();
});
The gif image is not showing with this code. I tried removing the $('#loading_image').hide(); and i discover that the loading of image happens after "long code processing"
Although I haven't test it, my guess is that the show() function uses the setTimeout function. Even with the timeout set to 0 miliseconds, this will change the order of the statements. Use the callback-option of show to make sure the long code processing is done after showing the image:
$('#run_only').click(function(e) {
$('#loading_image').show(0, function(){
//long code processing
$('#loading_image').hide();
});
});
This can be one aspect of asynchronous programming that is hard to reason about. Consider this example:
$('#run_only').click(function(e) {
$('#loading_image').show();
$.getJSON('/something.json?wait=3seconds', function() {
//This code will take about 3 seconds to execute
});
//This code will execute as soon as the $.get is fired (before it has returned)
$('#loading_image').hide();
});
To fix this try something like this:
$('#run_only').click(function(e) {
$('#loading_image').show();
$.getJSON('/something.json?wait=3seconds', function() {
//This code will take about 3 seconds to execute
//But this will only execute after the $.getJSON() is sucessful
$('#loading_image').hide();
});
});

Javascript 'console' infinite loop

I'm experimenting with javascript programs and I hit a snag. The program suddenly lags my browser (infinite loop maybe), dunno why.
function fullscreen() {
if (document.body.requestFullScreen) {document.body.requestFullScreen();}
else if (document.body.webkitRequestFullScreen) {document.body.webkitRequestFullScreen();}
else if (document.body.mozRequestFullScreen) {document.body.mozRequestFullScreen();}
}
var bash = document.createElement('span');
bash.setAttribute('id', 'bash');
document.body.appendChild(bash);
var cursor = document.createElement('span');
cursor.setAttribute('id', 'bashCursor');
cursor.textContent = '_';
cursor.style.display = 'none';
cursor.style.fontWeight = 'bold';
document.body.appendChild(cursor);
window.Bash = {};
window.Bash.printing = false;
window.Bash.queue = Array();
window.Bash.span = bash;
window.Bash.span.cursor = cursor;
delete bash; delete bash;
function bashPrint() {
window.Bash.writing = true;
var bash = window.Bash.span
var i;
while (window.Bash.queue.length) {
if (window.Bash.queue[0] == undefined) {
i = 0;
while (i < window.Bash.queue.length) {
window.Bash.queue[i] = window.Bash.queue[i+1];
console.log('l:'+window.Bash.queue.length);
console.log(window.Bash.queue);
delete window.Bash.queue[i+1];
window.Bash.queue.splice(i,1);
i++;
}
} else if (window.Bash.queue[0]['type'] == 'instant') {
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
} else if (window.Bash.queue[0]['type'] == 'wait') {
setTimeout(bashPrintWaiting, window.Bash.queue[0]['wait']);
break;
} else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
} else {
window.Bash.span.cursor.style.display = 'none';
}
}
}
window.Bash.writing = false;
}
function bashPrintWaiting() {
window.Bash.writing = true;
var bash = window.Bash.span;
bash.textContent += window.Bash.queue[0]['value'];
delete window.Bash.queue[0];
window.Bash.queue.splice(0,1);
window.Bash.writing = false;
setTimeout(bashPrint, 0);
}
function bashWrite(string) {
var array = Array();
array['type'] = 'instant';
array['value'] = string;
window.Bash.queue[window.Bash.queue.length] = array
}
function bashPause(times, string) {
if (!string) {string='';}
while (times > 0) {
var array = Array();
array['type'] = 'wait';
array['value'] = string;
array['wait'] = 50 + Math.floor(Math.random()*450);
window.Bash.queue[window.Bash.queue.length] = array;
times--;
}
}
function bashCursor(enabled) {
var array = Array();
array['type'] = 'cursor';
array['value'] = enabled;
window.Bash.queue[window.Bash.queue.length] = array;
}
bashWrite('Uncompressing');
bashPause(12, '.');
bashWrite('OK\n');
bashPause(3);
bashWrite('Build v. 0.1.01-release (x86_64-pc)\n');
bashPause(2);
bashWrite('Connecting');
bashPause(35, '.');
bashWrite('Error, unknown user. See connect.log for futher information.\n');
bashPause(2);
bashWrite('none#m ~ $ >>');
bashCursor(true);
bashPrint();
I uploaded it on jsFiddle - http://jsfiddle.net/uQcCP/
Program freezes between:
bashWrite('Error, unknown user. See connect.log for futher information.\n');
and
bashPause(2);
Please, can you help me? Thanks a lot.
The infinite loop starts on line 51: while (window.Bash.queue.length) {
It then ends up in the if statement on line 74, and within this the queue is never shortened:
else if (window.Bash.queue[0]['type'] == 'cursor') {
if (window.Bash.queue[0]['value']) {
window.Bash.span.cursor.style.display = 'inline';
If you find yourself having infinite loop problems in Chrome, open up your development tools and go to the script tab before you open up the page. After you open up the page and it starts looping, you can click the pause button to throw a breakpoint wherever the code is currently executing. From there it's a lot easier to divine where you're getting your error.

Categories

Resources