user736893
user736893

Reputation:

Ensure specific function is called last (maybe asynchronously?)

I have the function below in the $(document).ready(function(){}) which works well and populates lots of fields, depending on the record viewed. The problem is, on records with LOTS of results this executes before many images on the site are loaded (including the main logo and the loading indicator). Is there any way to ensure this code is called LAST?

$('.WorkstationCount').each(function (i, val) {
    $.ajax({
        url: 'details.svc/getWorkstationCounts',
        type: 'GET',
        data: { 'packageid': this.id },
        dataType: 'json',
        success: (function (el) {
            return function (count) {
                $(el).html(count.d);
            };
        })(this),
        error: function (a, b, c) {
            $('.Toast').html('Error Retreiving Workstation Count!');
        }
    });
});

I tried wrapping it in a function

function populateCount() { }

and then calling

window.setTimeout("populateCount", 1);

but then it no longer populated the data at all.

Upvotes: 1

Views: 2208

Answers (2)

gen_Eric
gen_Eric

Reputation: 227240

window.setTimeout("populateCount", 1);

This line is not correct. You do not need the quotes (or window.). It should just be:

setTimeout(populateCount, 1);

When a string is passed to setTimeout, it gets evald. It should have been setTimeout("populateCount()", 1);, but it's better to just pass a function to setTimeout.

Upvotes: 1

Alex Turpin
Alex Turpin

Reputation: 47776

If you need something to happen after all images of a page have loaded (although I don't understand why this is desirable), you can use the window.onload event.

window.onload = function() { alert("Page loaded"); }

Upvotes: 2

Related Questions