0

I'm a beginner in JS and Chrome extensions as I came there from the PHP-world. So I have a piece of code in my background.js:

 function findAtab(regex){
    var t = false;
    alert('t1: '+t);
    chrome.tabs.getAllInWindow(function(tabs){
        tabs.forEach(function(tab){
            if (regex.test(tab.url)) {
                t = tab.id;
                alert('t2: '+t);
            }
        });
    });
    alert('t3: '+t);
    return t;
}

var someRegex = /^https?:\/\/(?:[^./?#]+\.)?somesite\.com/;

var theTab = findAtab(someRegex);

Now when I run the code it shows me t1: false, then t3: false, and finally t2: 1060 (I have a tab with a compatible site opened). Why is that? As I understand it has something to do with the way JS executes code, (singlethreaded?), but where to dig?

Timkolm
  • 185
  • 1
  • 1
  • 7
  • Also see: [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321) – Makyen Aug 08 '17 at 21:35

1 Answers1

1

This is because getAllInWindow is a asynchronus function. This means that it will get pushed to a different heap (if I'm correct) to be excecuted. After the function is done, it gets pushed back to the Javascrip event loop, to be queued as the last item in the loop.

So what happens is: t1 gets called and you see an alert, the getAllInWindow gets called and pushed to the other heap. Then t3 gets called and alerted to the window. Now t2 has completed and pushed back into the event loop just to be excecuted as the third item in the row, and create some confusion for you :)

It might be good to read some more into this here: Javascript event loops This one helped me a lot to understand this situation: Philip Roberts: What the heck is the event loop anyway?

Bas Pauw
  • 262
  • 1
  • 12