mmmmm
mmmmm

Reputation: 605

Javascript synchronous timeout in while loop

I am trying to fake synchronous JavaScript while doing an AJAX request. I have an getPagePath(id) function that needs to get the page path of an page by giving it an page ID, it receives the data trough an web API. I thought this was going to be simple, just do an ajax request to the server and receive the page path. But what is happening: when requesting the page path my code keeps running and returns an empty var, after that the ajax call finishes, but to late.

I know my explaining is not much saying so here is my code:

var getPagePath = function() {

    // Function to check if this.pagePath is set.
    var pagePathReady = function() {
        console.log('PAGEPATH: CHECKING');
        if (this.pagePath && this.pagePath != null) {
            return true;
        } else {
            return false;
        }
    };

    if (!pagePathReady()) {
        // No pagePath defined so lets set it.
        this._setPagePath();

        while (!pagePathReady())
        {
            // Not yet defined, check again..

            // *** The problem ***
            // This while loop is running insanely fast making the browser crash.
            // How can I make this wile loop pause for 1 sec?
            // *******************

            console.log('PAGEPATH: NOT READY -> CHECK AGAIN');
        }

        // READY
        console.log('PAGEPATH: READY -> VALUE: ' + this.pagePath);
        return this.pagePath;
    } else {
        return this.pagePath;
    }
};

var _setPagePath = function() {
    if (!this.pagePathRequestFired) {
        this.pagePathRequestFired = true;
        // Fire request.
        system.url(
            this.getNodeId(), 
            function(url) {
                // Request ready, set pagePath.
                this.pagePath = url;
                this.pagePathRequestFired = false;
            }, 
            this
        );
    } else {
        // Call already running..
    }
};

I have set the problem in the more explaining comments.

Thanks in advance!

Upvotes: 0

Views: 1072

Answers (2)

goat
goat

Reputation: 31813

You can make an ajax call synchronous if you really need to.

xmlhttp.open("GET", "url", false);

Note the 3rd param.

But, I think you just need more practice in writing your code to work with the event/callback concept.

Upvotes: 1

Jason Kulatunga
Jason Kulatunga

Reputation: 5893

Instead of polling the pagePath (which doesn't seem to be required IMHO) why not just execute a callback when the _setPagePath is ready? If you want to fake a synchronous request, you can just display a loading spinner to the user as an overlay, disabling the UI.

Upvotes: 1

Related Questions