When you consume any food or drink containing carbohydrate or sugar, the bacteria in the plaque on your teeth metabolise it, producing an acid attack which lasts for at least 20 minutes. The acid dissolves the outer surface layer of the teeth (enamel).
The acid attack will be much longer if the food remains stuck onto the teeth, or if snacking continues over a period of time, eg. eating a bag of sweets one by one, or continuously licking a lollipop. Also, If babies or toddlers fall asleep with a bottle, or whilst nursing, the milk will remain on their teeth for a longer period of time.
If food and drinks containing sugar are limited to mealtimes, with sugar free snacks and drinks in between, the teeth can recover from these short periods of acid attacks. In the early stages of decay (before a cavity is formed), the enamel can repair itself by taking in minerals from saliva. Fluoride also helps to strengthen the enamel in this process.
However, with frequent snacks and drinks containing sugar, cavities become much more likely to occur. Once the enamel layer crumbles, a cavity is formed, bacteria enter and the decay process spreads rapidly.
To prevent dental decay, the aim should be to reduce the amount of time that any food containing sugar is present in the mouth. Drinking water or rinsing after eating can help. Try to make snacks and drinks, between meals, sugar free as far as possible.
Regular, thorough brushing to remove plaque build-up from the teeth will also help but, as it is not possible to prevent plaque from building up again after brushing, diet is of extreme importance in preventing cavities.