expand-collapse work as expected + according to your first post the collapse did work.
and the code you posted is also fine. So the problem is probably somewhere else.
Maybe the time on your computer is not correctly set.
(The code you wrote uses the OS computer time).