Ari Lotter
Ari Lotter

Reputation: 615

Is there an infinite loop in my code?

My webpage crashes when I run this:

function replace()
{
    var str = document.getElementById('feeds');
    var cont = str.innerHTML;
    curstring = "twitter: ";
    while (cont.indexOf(curstring))
    {
        replaced = cont.replace(curstring,"TWIMG ");
        str.innerHTML = replaced;
    }
}

Upvotes: 0

Views: 161

Answers (4)

Alnitak
Alnitak

Reputation: 339786

Probably, yes.

Your cont.indexOf() test should test for >= 0, since on not-found that function returns -1, which evaluates true and will cause the loop to go around again.

It'll currently only terminate if cont starts with curstring.

Per other answers, you also need to overwrite cont inside the loop too.

function replace() {
  var curstring = "twitter: ";
  var str = document.getElementById('feeds');

  var cont = str.innerHTML;
  var old = cont;

  // NB: indexOf() returns -1 on failure, so you
  //     must compare against that,
  while (cont.indexOf(curstring) >= 0) {
    cont = cont.replace(curstring, "TWIMG ");
  }

  // taken outside the loop so we don't modify the DOM
  // over and over if the match is repeated - only update
  // the DOM if the string got changed
  if (cont !== old) {
    str.innerHTML = cont;
  }
}

Upvotes: 1

nobody
nobody

Reputation: 10645

Yes cont never changes in the loop so if cont.indexOf(curstring) is true it will be true forever and your program goes into an infinite loop.

Upvotes: 0

scessor
scessor

Reputation: 16115

Yes, when curstring is in cont. In your while loop cont won't be changed, so cont.indexOf(curstring) will always be true.

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78520

Yes there is. You never reassign cont. Perhaps try this?

function replace()
{
  var str = document.getElementById('feeds');
  var cont = str.innerHTML;
  curstring = "twitter: ";
  while (cont.indexOf(curstring) != -1)
  {
    replaced = cont.replace(curstring,"TWIMG ");
    str.innerHTML = replaced;
    cont = str.innerHTML;
  }
}

Upvotes: 0

Related Questions