This is a common issue that new programmers face, especially when dealing with AJAX calls. Even more experienced programmers can have a difficult time grasping AJAX functionality. It's important to remember what the A in AJAX stands for, Asynchronous. This means that the main program will continue to run while another, side program will work to complete some other task, usually referred to as threads. In this instance, you are trying to return miningTime
by getting a value from that Asynchronous call. Because that AJAX call is running on a different thread from the main program, miningTime
will always be null.
In order to implement this correctly, you need to implement what is known as a callback function. A callback function is a function that is run when an Asynchronous program finishes doing what it was doing.
This is how it should be structured:
function GetTime(callback) {
var xhr = new XMLHttpRequest();
xhr.onload = callback
xhr.open("GET", "../php/mineTime.php", true);
xhr.send();
}
function callbackFunction() {
var timeToMine = parseInt(this.responseText);
console.log(timeToMine); // outputs: NaN
var display = document.querySelector('#time'),
timer = new CountDownTimer(timeToMine),
timeObj = CountDownTimer.parse(timeToMine);
...*code continues*
}
window.onload = function () {
var callback = callbackFunction
GetTime(callback)
}
Note that in Javascript, there are other possible ways of handling this as well. There are things called Promises
as well as async/await
. This is, in my opinion, the simplest and most vanilla way to do it.
Update: Since you can't have a function with a time parameter, what you can do instead is pass a reference to the function instead. Referencing a function is sort of like copying a function and pasting it somewhere else, whereas calling a function actually runs it. You can discern the two by the parentheses. If open and close parentheses are added after a function name, it will call the function, if they are omitted, the function will merely be referenced.