1

I have problems with a line of code in javascript. I have done a funtcion:

function evvalt(valtoztat){
    for(i=0;i<12;i++) naptar(valtoztat);
}

If I do this way, then the browser freezes out. There is no problem with the naptar(function) it works perfectly. The interesting side of this problem the next:

function evvalt(valtoztat){
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
    naptar(valtoztat);
}

There is no problem this code.. :O I would like to know what the problem is.

Thank you for your assistence, David

5
  • 1
    You got an infinite loop that's what happens.. Commented Apr 5, 2015 at 17:43
  • What happens when you do for(var i=0; ...? Commented Apr 5, 2015 at 17:46
  • Try not to use the shorthand syntax also, use brackets { } Commented Apr 5, 2015 at 17:46
  • How? If the naptar() function works well, using it in a for loop which do the naptar() function in one line, why could cause infinite loop? Commented Apr 5, 2015 at 17:47
  • Thank you the codefor(var i=0; ...` works well!! :) Commented Apr 5, 2015 at 17:56

2 Answers 2

3

Since you have not declared the variable i as a local variable it is being treated as a global variable and it is likely that something in your naptar() function is also changing the value of i causing an infinite loop.

Add var in front front of the use of i like this to make it a local variable:

function evvalt(valtoztat){
    for(var i=0;i<12;i++) naptar(valtoztat);
}

And, also look in naptar() for a place where you are using i without declaring it as a local variable (or in any functions that naptar() calls). You should ALWAYS declare local variables with var within the function so they do not become implicit globals.

Even better, starting using strict mode in Javascript where creating an accidental global like this becomes an error rather than a silent bug.

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

1 Comment

Thank you for your help! This solved the problem :) I do my first things in this language and I haven't know that. I had written everyi for-loop variable ( there weren't any written as you said).
0

you are poluting global space so there is a chance that you change your 'i' somewhere else.

rather do:

for (var i = 0, i < .. , i++) {..

if you do the for loop the same way somewhere else no wonder that it's not working.

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.