Search code examples
javascriptgoogle-chrome-extensiondelaygoogle-chrome-app

Is there some delay for javascript when executing a function


I am experimenting with creating a chrome extension, and I am running into a very strange problem when my javascript is executing. Some of the code seams to be running on a delay.

Here is the code:

var windowArr = new Array();

function create(t) //t = tab to create new window with
{
    newWindow = new Object();
    newWindow.tabId = t.id;
    chrome.windows.create(newWindow, function(w){windowArr.push(w.id);}); //w = new window

    // Here is where it gets weird
    alert(windowArr[0]);// returns "undefined"
    alert(windowArr[0]);// returns "573" // the correct value
}

The delay is messing up other parts of my code.

What could be causing this?


Solution

  • chrome.windows.create is asynchrounous.

    So you should insert it inside the callback, or in another function called inside it.

    The second alert works because while you dismiss the first alert box, the window has been created. (and the array is filled)

    here an example:

    chrome.windows.create(newWindow, function(w){
        windowArr.push(w.id);
        step2();
    });
    
    function step2() {
        alert(windowArr[0]);
    }