Ok,I've been trying to get this to work for the past two days and I cannot figure out what I am doing wrong. I have a function called "ping" that makes a calculation, and I have a callback function to retrieve the calculated value, but all I keep getting is undefined!
var test;
var p = ping('apple.com', function (num) {
test = num;
console.log(test); //this works, the value is displayed in the console.
});
console.log("p: " +p); //says undefined
console.log("test: " +test); //says undefined
Can someone tell me what I am doing wrong? Thanks!
Edit: Here is the ping function:
function ping(host, pong) {
var started = new Date().getTime();
var http = new XMLHttpRequest();
http.open("GET", "http://" + host, /*async*/true);
http.onreadystatechange = function() {
if (http.readyState == 4) {
var ended = new Date().getTime();
var milliseconds = ended - started;
if (pong != null) {
pong(milliseconds);
//console.log(milliseconds);
return milliseconds;
}
}
};
try {
http.send(null);
} catch(exception) {
// this is expected
}
}