I have written a script in JS, and tested it in Mozilla Firefox on Ubuntu. The code didn't work at first, so I had to debug it.
Then I found that the script was proceeding depending on where I set breakpoints in debug mode.
So if I set breakpoints as shown in the first screenshot, I get coffebrake
var's value equals 0 (but it should be 1).
And if I go into the getVar
method, as shown in the screenshot with going down in getVar method, I get coffebrake
equals 1, as planned.
If I use this script in normal mode, it gives results as in the first case, when I didn't set breakpoint in getVar
method.
What is the problem? And what should I do to get proper results?
The problem with your code is that you're using an asynchronous HTTP request to get the data, but you're not waiting for it to complete before accessing responseText
. Here's an outline of the problem:
XMLHttpRequest
using the open method and indicating that you want an async request with the third parameter: the rest of the code will not wait for the result of the request to complete but rather return as soon as possible.send
method without having set a status call handler. Without one you have no way of knowing when your data is ready. See the docs. You should really be setting the onreadystatechange
handler before calling send
.null
. Since you're coercing the value to Number
, it will be converted to 0, which is what you're seeing.Long story short: make sure to set onreadystatechange
before calling send
and wait for the data to be there before querying responseText
. Also, check for errors :)