Fainting or sudden loss of consciousness is a problem which occurs because of sudden drop of blood to brain which can be caused because of many different reasons.
Anemia, low blood pressure, heart or nervous system issues and low glucose level are usually the reason of sudden fainting.
There are number of symptoms through which you can know that fainting is approaching and you are never to collapse. Lightheadedness, blurred vision, ringing in your ears and sudden sweat are the most common symptoms.
If you recognize the symptoms then you can avoid fainting. If you are standing then you should immediately lie down or sit down and place your head between your knees. This helps in restoring the blood flow to the brain.
Also make sure that you are in a place which is not dangerous if you faint. If you are on stairs then move away or sit down in a position that you do not fall down in case you faint.
Usually you will recover within 2 minutes because blood flow resumes to your brain within minutes.