This can be accomplished in three ways: Destroying all the enemy's Troops, leaving few enough that the attacker fails to destroy the Headquarters or Outpost before the time runs out, or forcing the attacker to retreat.

When a Defense can Happen

Countdown that appears after a total of 3h 30m online in a day (Countdown starts at 30m)

Defenses can only happen when you are offline.

The exception to this rule is when you have played for more than a total of 4 hours in one day. After that, you will still be able to play normally, but you could be kicked offline and attacked at any time unless you are attacking a base. After the defense is over, you can return to the game.

30 minutes before you reach the 4 hour limit, a red countdown timer will appear beside your diamond counter, notifying you of this. Once reached, another red countdown timer follows, representing the interruption period where you can be attacked when online. This timer will be active for the rest of the day and will end simultaneously with that day's event.

There is no "cooldown" or "shield" that protects your base after a defense, so as long as there are players with your base on their map, you can be attacked again.

Being Attacked

Message shown when attempting to log in during an attack against your home base

You cannot see the outcome of a defense until the attack is over. Until that time, a message will appear and the player will be unable to interact with the game.

If your base's defenses are successful in repelling the attack, you will lose nothing.

When logging in after a defense, buildings on your base that were damaged will be shown recovering health. This is purely for show, however. After a defense, your buildings will be fully repaired for the next one. You do not need to log in after a defense to repair your buildings.

An attack against your base will never result in any permanent damage.

Defense Rewards

Diamonds and Intel earned on a home base defense (regardless of whether the defense wins or not) are related to how many housing space worth of troops are destroyed. Any rewards earned from an attack on your base can be claimed from the attack's entry in your Activity Log.

Note that you are unable to gain more than 4 Intel from the same attacker. Successive attacks by the same attacker will continue to award Diamonds if enough troops are destroyed, but Intel is capped at 4 per attacker.

No rewards are earned for troops destroyed in an attack against one of your Resource Bases.

There's an achievement which is called Strategist that gives a total of 60 gems upon successfully defending your home base against a total of 800 attacks.