Ending the Encounter
You can decide a fight is over if there's no challenge left and the player characters are just cleaning up the last few weak enemies. However, avoid doing this if any of the players still have inventive and interesting things they want to try or spells they're concentrating on—ending an encounter early is a tool to avoid boredom, not to deny someone their fun. You can end a fight early in several ways: the foes can surrender, an adversary can die before its Hit Points run out, or you can simply say the battle is over and that the PCs easily dispatch their remaining foes. In this last case, you might ask, “Is everyone okay if we call the fight?” to make sure your players are on board.
One side might surrender when almost all its members are defeated or if spells or skills thoroughly demoralize them. Once there's a surrender, come out of initiative order and enter a short negotiation. These conversations are really about whether the winners will show mercy to the losers or just kill or otherwise get rid of them. The surrendering side usually doesn't have much leverage in these cases, so avoid long back-and-forth discussions.
Fleeing Enemies
Total Party Kills
TPKs are rarely unavoidable. Usually it becomes evident at some point during the session—whether to everyone or only to you—that disaster looms. What the players do with this insight is up to them, but you have more control and can take steps to avoid the TPK. For example, perhaps the PCs' foe gets distracted by something, an ally arrives to help the heroes, or the villain captures them instead of slaying them outright. The simplest path is to just allow a clear escape route the PCs can take—perhaps with a few characters still falling along the way. It isn't entirely your responsibility to defuse the TPK, but offering such opportunities gives players more say in their characters' fates.
Should a TPK occur anyway, the kind of game you're running should influence your approach to the situation. For example, in a relatively story-light campaign centered around dungeon crawling, a TPK is less of a problem—the players simply form a new adventuring party and take up where the dead ones left off. If you're running a story-intensive game in which each PC has a personal stake in defeating the villain, saving the city, or the like, a TPK could require you to rework multiple plot threads. Here, you might use the story you have in place; for example, a player's new character might be the sibling of their previous, slain character, thus creating some continuity between the two characters and ensuring that the new character still has a stake in defeating the villain.
Note that the game should continue only if the players want it to. The premature end of an adventure or campaign isn't always a bad thing. If the group is interested in moving on, there's nothing wrong with ending the campaign and starting something different.