This phenomenon is called 'focus hunting'. It happens when the autofocus system repeatedly overshoots the correct focal distance (too far, too close, too far, too close...). Sometimes strong vertical or horizontal lines in the image can confuse things, depending on the system your camera has. Shooting in low light is also difficult for a lot of systems. If you can switch off the autofocus, focus the camera where you want it and leave it on manual. This works best for stationary subjects, but if there is a lot of motion you may be forced to keep it on auto.