Javascript and Geogebra interaction (race conditions?)

artydent shared this question 2 years ago
Needs Answer

I was encountering some problems with Javascript: It seems that after sending a command to Geogebra the script doesn't always wait for changes in Geogebra objects to manifest, thus creating a race condition and potentially producing wrong results if the remaining script depends on those objects. Is this generally the expected behaviour (or possibly just undefined behaviour)? If yes, is there a standard way to make the script wait or should scripts simply not be used with such kind of interaction?

Here's a small example that illustrates this issue:

Upon changing of a value of n a script is called that tells Geogebra to generate the divisor list, then to get the length of the resulting list, then this length is copied to a JS variable. Turns out, the JS variable always gets the previous list size from before the list changed.

ggbApplet.evalCommand("DL = DivisorsList(nn)");
ggbApplet.evalCommand("DLsize = Length(DL)");
var listsize = ggbApplet.getValue("DLsize");
alert("listsize: " + listsize);

Interestingly, this problem doesn't occur if instead of the divisor list a sequence is created, even a long one that takes a few seconds to create. Which leads me to belief that the script is actually supposed to wait but something goes wrong in the first case.

Attached are the problematic version with the divisor list and the okay version with the sequence.

Comments (2)


does it the same if you use ggbApplet.evalCommand("SetValue(DL , DivisorsList(nn)") instead ?


Same problem if I replace the two "=" assignments by "SetValue" commands. Except that with "SetValue" also the Sequence version has this behaviour where the JS variable gets the previous list size.

Edit: A workaround is to have the script delete the DL object at the start. (That's why I did that in in the triple factorization script from the other thread.)

Side note: then "nn" was a typo and was supposed to be just "n". Not that it matters for the actual problem here (just a different list), but it makes me wonder why Geogebra automatically treats this as n*n (if no variable named "nn" exists). I think that's the kind of unnecessary "convenience feature" that barely adds anything (and even feels unintuitive to me) but reduces the chance to detect unintentional typos.

© 2023 International GeoGebra Institute