Check with the debugger what the code is actually doing. The issue is probably not with the code you posted but rather it may get called with a different parameter again unexpectedly.
Do note that it is very bad style and prone to errors to write a conditional the way you did because you already tested if visible is true, you must not test again if it is false.