Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Javascript need an anonymous function to delay execution?

In my application I need to conduct an IP lookup as a prerequisite to proceeding with execution of another function that needs that data. Originally, I called the function as follows:

$(document).ready(function(){

var ipUrl = "myURL?callback=?";    
$.getJSON(ipUrl, function(data) {
        window.ip = data['ip'];
        console.log("inside function" + window.ip);
    }).done(printIp());
});

function printIp() {
    console.log("function is done " + window.ip);   
}

However, this outputs as

function is done undefined 
inside function <ip_address>

I.e. the printIp() function is called before the $.getJSON is actually complete.

If however, I wrap the printIp() call within an anonymous function as follows:

$.getJSON(ipUrl, function(data) {
    window.ip = data['ip'];
    console.log("inside function" + window.ip);
}).done(function() {
    printIp();
});

I get:

inside function <ip_address>
function is done <ip_address>

As I would expect. What is going on here? Why do I need to wrap the function call in an anonymous function?

like image 484
ronan_mac Avatar asked Feb 02 '26 08:02

ronan_mac


2 Answers

your code says

}).done(printIp());

what this does is calling printIp and using the result of the function call as an argument to the done method.

what you actually want is passing the function as a done handler. use }).done(printIp); to do this instead.

like image 162
collapsar Avatar answered Feb 05 '26 01:02

collapsar


You are executing printIp right away. Try it without the ():

$.getJSON(ipUrl, function(data) {
    window.ip = data['ip'];
    console.log("inside function" + window.ip);
}).done(printIp);
like image 33
Amberlamps Avatar answered Feb 05 '26 01:02

Amberlamps