To get badge, you need to defeat that gym leader. If you lose, you need to wait 24-48 hours before rebattling him/her, the cooldown time varies between different gym leaders.
For npc, if you lose, you cannot rebattle them again, until 2 weeks later, when the npcs are reset and you can rebattle them then, but i heard that the cd time for some npcs is different.