1
for (i = 0; i < 100; i++) {
  botManager();
};

only executes once

botManager();
botManager();
botManager();

but this executes 3 times. I'm baffled. I've tried debugging with console.log and debugger; but to no avail. What are common solutions?

16
  • you want botManager to execute 100 times? or wht? Commented Feb 18, 2017 at 7:05
  • seems like your botManager function calling other functions which are taking too long to complete while the loop execution is quite faster as a result you are not getting any result.. you can add timeout function to add some delay and if botManager return some result you can use chaining to make them synchronous... Commented Feb 18, 2017 at 7:05
  • change your i to 3 and try to step through your code Commented Feb 18, 2017 at 7:09
  • You could start with an empty implementation of botManager and add more code along the way until you see the current behavior. Commented Feb 18, 2017 at 7:15
  • for loop will just break if the nested functions haven't finished their job by the time botManager() is called again by the for loop (which is 1 ms) Commented Feb 18, 2017 at 7:17

1 Answer 1

5

Give scope to loop variables

for(let i = 0; i < 100; i++)

Everywhere you are using for loops. Or better yet use 'use strict' at start of page.

Because if you have other(s) for loops that use i in the functions that are being called inside the main for loop, then that could be causing problems.

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

6 Comments

Thank you, jesus. 'Let' works great and now Ill try strict. I had no idea let even existed.. knew I was missing something though!
While this may solve the problem, it doesn't help in understanding the problem. The code as shown in the question cannot possibly have the problem as stated. JavaScript does not get "busy" or "tired" and "forget" how to run a loop. It just doesn't work that way. The problem lies elsewhere, in code that was not shown in the question. Now, if some of that other code is asynchronous code that depends on the value of i, that is a different matter. But we can't possibly know that from the code shown in the question.
Also the browser support of the let should be taken into account.
@MichaelGeary Yes, I'm sorry about that. I tried to guess what was going on but I couldn't post my guessing as a comment because I lacked enough reputation points back then so I didn't have any other option but to post an answer.
@ThanasisGrammatopoulos My answer was edited. Previously I had var i and after the edition it became let i.
|

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.