0

UPDATE: The problem I am having stems from something entirely different, I would delete the question alltogether but since there are answers, I am not allowed to. /OP

I have a script that is very complex and hard to distill, but here is the essence of what I am doing:

var modulesCount = 4;

// setup the modules object
for (var i = 1; i <= modulesCount; i++) {     
   composeModule(i);
}

I have some strange behaviour, where is seems every call to the function composeModule() isn't made, so I figured, will I have to use a setTimeout in order to split the thread into say 4 different threads like this? Say like this:

// setup the modules object
for (var i = 1; i <= modulesCount; i++) {     
   setTimeout(function() {
       composeModule(i);
   }, 1);
}

------------------- UPDATE

Tried this

    var c = 1;
    for (var i=1;i<=modulesCount;i++) {     
       console.error('actual count is: '+c+' while variable i is: '+i);
       self.composeModule(i,initialCall);
       c++;
    }

to check if there is a problem with my variable i but it is identic to c in every console output. Or did I misunderstand you guys'es point entirely?

Matt Welander
  • 8,234
  • 24
  • 88
  • 138
  • 1
    JavaScript isn't really a multithread capable language – Sterling Archer Feb 07 '14 at 16:13
  • 2
    Why do you think all the function calls aren't being made, and why would sprinkling in `setTimeout` calls fix it? I'm not following at all. – John Kugelman Feb 07 '14 at 16:13
  • Can you use `console.log` or **https://github.com/flatiron/winston** to log some messages in your code? I have a hard time believing the loop will not call `composeModule` 4 times. Maybe your issue is somewhere else. – Jess Feb 07 '14 at 16:17
  • Please put a `console.log` inside `composeModule` and also share that source if you can. – Jess Feb 07 '14 at 16:40
  • 1
    you're right, my problem lies elsewhere, it does get called 4 times like intended. So should I delete this question? I also have 3 votes to close so I will just go ahead and delete it all together. – Matt Welander Feb 07 '14 at 16:42

2 Answers2

1

If you really want to write that loop, you need to put the variable i into a closure:

// setup the modules object
for (var i = 1; i <= modulesCount; i++) {     
   (function (inner_i) {setTimeout(function() {
       composeModule(inner_i);
   }})(i), 1);
}

See JavaScript closure inside loops – simple practical example

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

To split threads in javascript there is a new function called web worker. A worker is, as a rule of thumb, something similar to a Thread in Java.

Refer to the following to gain more insight: https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers

markusthoemmes
  • 3,080
  • 14
  • 23