Valves are timed so that they open to let air in and exhaust fumes out, and so that they open and close fast enough to not get hit by the piston. The timing is controlled by the camshaft, which also controls how far they open.
Valves must open and close at specific times to provide basic engine functionality, with the intake valves open during the intake stroke as the piston pulls air in, and the exhaust valves opening when the piston needs to push the used exhaust gasses out. However, the exact time these occur can be altered slightly for performance gains, towards power or efficiency. In some engines, the exhaust valves will still be slightly open when the intake valves open, which allows for improved movement of air within the combustion chamber.