All hope is lost, soon the Big Bad will achieve his/her goal of taking over/destroying the city/world/universe and there's nothing the heroes can do to stop them. Then WHAM! Something unexpected happens, and the tide turns in the heroes' favor, allowing them to overcome the villain and win.
This is what we call a Near Villain Victory, where the bad guys look like they're going to win only to get defeated at the last moment.
It is a given that in battles between the forces of good and evil, the heroes will win 99% of the time and the villains will be defeated in the end. So, the writers will come up with scenarios that stack the odds in the villains' favor and give them minor victories, thus raising tension by getting the audience to think that maybe this time the hero won't save the day.
Often, it's the very fact the villain is so close to victory that results in their downfall. They've got the heroes on the run, maybe they've got every right to think they're going to win or already have...then they get cocky. Because they already declared victory, they come to think the hero is no longer a real threat to them. Sometimes, they might even ignore the hero to focus on putting the finishing touches to their plan or announce themselves the supreme Evil Overlord, confident they've got nothing to worry about. This gives the heroes the opening to make a big, crippling blow when the Big Bad is least expecting it.
Note: There is in fact a very real and very specific word for this trope. That word is eucatastrophe. (It's also worthwhile to note who invented this word. Though J. R. R. Tolkien's definition stresses that somehow things go good, not solely because a group of hard working Badass heroes are turning it around, but because of some intervention or action beyond the heroes' control - in effect, a miracle - that makes victory possible.)
When this trope gets subverted and the villain still wins anyway, you have a Hope Spot.
Compare You Can't Thwart Stage One. Might overlap with Darkest Hour. Often used to set up a plot about coming Back from the Brink when it occurs in video games. If it gets bad enough, then Only the Author Can Save Them Now. In video games, the Instant-Win Condition can easily result in this trope.
open/close all folders
Anime and Manga
Occurs in the Cell Saga of Dragon Ball Z, when Big Bad Cell who was thought to have died when he self-destructed comes back thanks to his regeneration From a Single Cell and is now even STRONGER than Super Saiyan 2 Gohan. Cell launches a MASSIVE Kamehameha wave with the intent of blowing both the Z-Warriors and the earth away and it's all Gohan can do but hold him off in a Beam-O-War struggle which he is slowly losing ground in (the anime, which thankfully was kept in Kai, included the Z-Warriors helping out by firing energy blasts at Cell from behind. Though he manages to deflect them through pure energy alone). Then all of a sudden, Vegeta blasts Cell from behind distracting him long enough that Gohan can push both Kamehameha waves back at Cell, killing him off for good.
At around the same time of Vegeta's attack, Goku (who recently died to save the planet from Cell's self-destruction) appeared in spirit form to tell Gohan that he's really still strong enough to kill Cell, because his broken arm doesn't actually do anything to weaken him.
In the movies, this is kinda Broly's thing. Example: Pre Villain Decay (well, we're talking about a show where the heroes are exponentially more powerful every season and the Return is about 10 years later), Broly is in a different league from the heroes, to the point no one in the entire cast can so much as stand toe-to-toe with him and trade blows. Broly is so powerful that the Blood Knight VEGETA is TOO SCARED to fight him until most of the cast is near death. Then Vegeta is put down in about 5 seconds. Goku, with the combined remaining power of the entire cast, lands one punch and it looks like Broly blows up from his own overpowered-ness. And then the planet blows up for unrelated reasons.
The Return: Well, teenage Gohan can go toe-to-toe with Broly now. Broly shows a tiny amount of what could be construed as fear when Gohan goes Super Saiyan 2... at which point Broly uses his "Legendary Super Saiyan" form, which is likely just Super Saiyan 2. And proceeds to No Sell anything Gohan throws at him. He reacts a little bit to being drowned IN LAVA. The following is possibly the most intimidating Out of the Inferno ever. Because, y'know, LAVA. The Gohan / Spirit Form Goku team Kamehameha from the Cell arc? Yeah, that's how they take Broly down for the count. With Spirit Goku, Gohan, and Goten, Goku's other son.
But only because a side attack from Trunks distracted Broly. Had Trunks not regained consciousness or if Broly ignored the attack, he almost certainly would have destroyed the Earth.
MÄR, atleast the anime version anyway. Everyone except Ginta, Babbo and Jack are dead, the Big Bad is attacking Earth, and it looks like all is lost. Then Snow merges with Koyuki to allow Ginta to use the magic stone inside of her to defeat the Orb and resurrect everyone. Think about that, if Snow hadnt died beforehand, everyone wouldve been screwed. The manga averts this however, with a laughably easy final battle in which none of the heroes even get so much as a scratch.
Mazinger Z: Often Dr. Hell and his followers were on the brink of winning, and only through of extreme competence and sacrifice of Kouji and his allies or of utter incompetence of Hell's minions, the situation was saved. It happened several times when they very nearly took the Institute over (the most prominent of them happened in episode 57) or invaded it successfully (episode 87), or managed to steal a sample of Alloy Z... However the most notorious of them happened in the last episode when Archduke Gorgon's Robeasts destroyed Mazinger-Z and demolished the Institute. Tetsuya's Big Damn Heroes moment saved Kouji's life, but the villains finally were victorious against Mazinger. That story was greatly expanded in the Mazinger vs Great General of Darkness movie.
In the Gosaku Ota manga episodes, Great Marshall of Darkness sucessfully blackmailed Japanese army into destroying Great Mazinger and the Fortress of Science. The army bombarded the Fortress and stormed into the place before blowing it up completely, and the heroes were forced to flee and lie low for a while. Meanwhile, Mykene army conquered Japan.
In the last episodes of the anime and Gosaku Ota manga, the Mykene army struck the Fortress and in the manga, Marquis Janus traped Misato and cut her in half, and attacked Mazinger-Z and Great Mazinger separately. Kouji and Tetsuya nearly got killed, and Prof. Kabuto commited a Heroic Sacrifice to save Tetsuya. The generals of the Mykene army laughed. Five minutes later they were not laughing.
UFO Robo Grendizer: One of the best examples happened in the two-part finale of the first season. Grendizer had been beaten by two Robeasts and forced to hiding, Kouji's TFO had been badly damaged, Blackie had taken control of the Science Space Center and tortured Dr. Umon. When Duke returned, he managed beat both mechas, saving his friends and destroying Blackie's command ship.
Sometimes subverted or outright averted, most notably in 5Ds, when Badass Normal Crow wipes the floor with some security guards in about one turn. Also, Yusei defeated Kiryu with 1400 LP on his second try, so the above rule might remain unwritten.
ROD the TV. Joker has Junior, with the intention of using his body to house the Gentleman (the former head of the British Library whose soul is in a set of books), and is set to brainwash the whole world into believing the British are all powerful (and somehow transforming reality into something 19-century). The heroes are there but since paper is their main weapon, there's none on hand. Trying to talk things out doesn't work. Nenene, who throughout the series was stressing over writing a novel and had only recently finished it, sacrifices the unpublished novel, which is more than enough artillery for Yomiko and the Paper Detectives to stop the baddies.
20th Century Boys uses this to great effect. Friend, for one, actually succeeds in ruling the world and being hailed and loved as the world's savior. It's only when he decides to destroy it, that things start to turn in our heroes favor.
Monster has one at the end when, following the Ruhenheim Massacre, Johan very nearly coerces Tenma into shooting him and thus corrupting himself forever by threatening to kill a young boy only to be shot in the head by the boy's father at the last minute.
The goal of the bad guys in Digimon Frontier is to destroy the digital world piece by piece and feed it to Lucemon, thereby freeing him from his prison. The heroes do all right at first, but then they come up against the Royal Knights, who repeatedly take out a chunk of the world and the heroes barely escape with their lives. Eventually the Knights succeed in taking the entire planet, forcing the heroes to take refuge on the moons. They're able to rally and take out the Knights at this point, but that still means Lucemon's back, and he's able to start an invasion of the human world before he's defeated.
Digimon Xros Wars does it twice. First it seems DarkKnightmon has completely absorbed his brother Bagramon till Bagramon fights back and absorbs him. Then Bagramon has the digital world and earth under his power, and prepares to destroy everything and remake everything in his will with the Code Crown power, and just he is about to finish of Taiki Shoutmon appears and saves him, because the Code Crown chooses Taiki over Bagramon, and the tables start to turning in favor for the good guys there.
Oh good Lord, Fullmetal Alchemist. In Chapter 104, the Big Bad, Father, absorbs the souls of everyone in the country and eats the Truth, making him powerful enough to conjure a sun in the palm of his hand. Luckily for the world, Hohenheim had a circle in place to reverse it, leaving Father in a state of Superpower Meltdown due to not having enough souls to contain Truth. At which point awesomeness ensued.
Tokyo Majin. The heroes are up against a God Mode evil spirit (Yagyu Munetaka) who eliminates all the main & supporting cast heroes—which adds up to a fight of about TWENTY on ONE. Only the resident badasses are even able to deal damage to him. With all your typical anime Badass superpowers present. There is much buildup that they're likely to lose unless they unlock all four Godbeasts to turn Hiyuu into what amounts to the ultimate hero of awesomeness. So, as most of the cast lies there broken, dead or dying, in from left field comes the final Godbeast's vessel and bam, the Hero of Ultimate Bullshit is awakened. Screaming J-Rock in the background. Hope Spot. Hiyuu STILL LOSES. And the heroes finally answer with their own God ModeHeroic Resolve as The Chick brings everyone back to life, declaring they will keep fighting until they win.
In Project ARMS, Alice has possessed Katsume, Ryo appears to have no choice but to kill them both, Keith White is quickly on his way to being a living god and destroying everyone on the planet to prove it, and the ARMS weapons - the only things that have a chance of stopping him - have been deactivated. It's only after Kei is able to appeal to Azreal and get the ARMS weapons back up that things start to turn in their favor.
Gundam ZZ: Neo-Zeon is in control for the series: the AEUG is barely hanging on and is little more than an annoyance to the revived Zeon. Then, just as Haman Karn is about to solidify her control over the Earth Sphere, an Enemy Civil War erupts and Neo-Zeon rips itself apart, allowing the Federation's previously-outmatched forces to come in and sweep up the pieces.
Also happened in the original Mobile Suit Gundam: early in the One Year War, the Battle of Loum saw Zeon wiping out most of the Federation fleet and capture its commander general Revil, and the Federation was about to surrender when Revil managed to break out and make a Rousing Speech that evidenced how Zeon was actually in worse shape than the Federation, resulting in the Federation soldiering on and continuing the battle. Even then, Zeon had invaded Earth and occupied most of Europe, North America, northern Asia and chunks of Africa. That's the situation at the start of the series, and it's only halfway through it that the Federation scores a decisive victory and retakes Europe and Asia, and it's hinted that the major contribute of the heroes is to distract Zeon's armies from the war by bringing a lot of firepower too near Zeon's major industrial hubs on Earth, forcing them to redeploy and giving the Federation much needed breathing space to marshal up its much bigger army and unleash it on Zeon's occupied territory.
This trope appears to be a favorite of Hirohiko Araki, as every villain of Jojos Bizarre Adventure often comes only a hair's breadth away from killing all the heroes, only to be defeated by circumstances they couldn't predict:
Battle Tendency: Kars finally becomes the Ultimate Life Form with Complete Immortality after obtaining the Red Stone of Aja. His triumph becomes his curse when Joseph reacting on instincts uses the Stone to launch Kars into space with a volcanic eruption. Kars is left adrift in space, trapped in a form that is half-mineral half-flesh.
Stardust Crusaders: Nearly all the heroes are dead, DIO has acquired a massive power boost that allows him to stop time on such a scale that Jotaro simply can't keep up, and in the end, DIO is defeated by Polnareff's intervention, and eventually, Jotaro becoming able to stop time himself.
Diamond Is Unbreakable: Kira acquires a seemingly foolproof power that allows him to constantly kill and rekill any potential witnesses until he's satisfied that his secret identity is complete. Only because of some quick thinking from Hayato are the heroes finally able to find him and defeat him for good.
Vento Aureo: Diavolo has nearly wiped out all opposition, and is only moments away from acquiring the Arrow, but is only defeated by Bucellati, Trish, and Giorno snatching it away from him in the last second.
Stone Ocean: Enrico Pucci succeeds in killing all of the primary protagonists (and in a round about way everyone on earth), and accelerating the universe through a second big bang. The only thing preventing a Downer Ending is Emporio defeating him at the last second with Weather Report, preventing the new universe from lacking a Joestar bloodline.
Steel Ball Run: This actually happens twice. Gyro dies, and Johnny is left to fight allone against the seemingly Nigh Invulnerable Funny Valentine. Crippled, without his horse, and with only one bullet left, Johnny finally understands Gyro's dying words and unlocks the ultimate form of his Stand. Following this, the alternate universe Diego Brando actually beats Johnny, rendering him helpless while Diego wins the race, and is just about to ensure that the Saint's Corpse will remain in his possession, when Lucy Steel arrives with the original Diego's head, which merges with the second Diego and blows his head up. For an extra kicker, since Diego can't claims his prize money due to being..well dead. He's disqualified and the it goes to a runner up. A much less jerk-ass character.
Classic Marvel tale where Kang The Conqueror realizes that all he needs to defeat the Avengers is to get a Robot Spider-man to join the team. The robot's turned away because no one liked Spider-man, so it makes up a story about knowing where missing teammate Iron Man is. On the rescue mission the robot systematically separates and takes out all the Avengers, but before he can finish them off real Spider-man shows up upset at the impostor and in battle figures out how to shut off the robot. Predictably, Kang learns of his failure and hangs his head in shame.
This plan worked so well though that when the robot got turned back on by accident it, once again, managed to subdue the current lineup of Avengers, and that wasn't even its goal this time. Luckily, Spider-man's clone happened to be in the area.
This trope seems to be very common for Kang; in the "Kang Dynasty" storyline, he nukes Washington DC and conquers the entire world. It takes a group of off-world heroes commanding a very powerful alien device to even begin to overthrow him, and they still would have failed except for some betrayal by Kang's son.
W.I.T.C.H.loves this trope, having pulled it in every major story arc at least once. The Trials of the Oracle arc takes the cake, as it does it three times: first the arc starts with Phobos taking over Kandrakar under everyone's nose, then the Guardians retrieve Elyon and gives her back the Crown of Light with her powers only to discover it was actually a transformed Cedric, and then, after Cedric has been recaptured and Phobos has thrown himself in the infinite to not be recaptured or having to face another No-Holds-Barred Beatdown at Will's hands (especially now that she doesn't have to hold back), ends with Phobos returning thanks to his ace in the hole and nearly defeating the Guardians before a chance accident frees them from his hold as he's real enough to be disintegrated.
Secret Wars has this. Doctor Doom takes the Beyonder's powers and becomes omnipotent. The heroes try to talk him into releasing his power and ... he destroys the lot of them. This is an issue cliffhanger. All the heroes die.
"The Black Bull of Norroway" is the example of eucatastrophe cited by Tolkien in "On Fairy-Stories": the heroine has, after a long and miserable quest, won her way to where the prince is. She can't get at him, though. She bribes the princess who intends to marry him, and gets to his bedchamber, to find that she can't wake him. (The princess drugged him.) She tries again. And again. And the third time, the prince had been told by some servants that someone had been begging him to wake up during the night, and doesn't drink the drug.
In the Jackie Chan Adventures fic Queen Of All Oni, Queen Jade, being Dangerously Genre Savvy, comes up with a plan to steal the captured masks. It's based off what happened when Dark Jackie stole the Talismans, and although the mask is attached to Captain Black, the plan still works to a point, Jade uses the mask to sneak into Section 13, and if it weren't for Wisker's interference, SHE WOULD HAVE SUCCEEDED!
All three of Trigger Happy Fanboy's Pokémon fanfics have these. And considering the fact that they're all in the same universe, they live in a pretty deadly world.
In the Forget Shipping duology (Let The Flames Begin/And Watch Cities Burn) Ghetsis has the Griseous, Adamant, and Lustrous Orbs, Brendan has been captured by Giratina in the Distortion World and is about to be eaten, and Lucas has lost to N. Team Plasma has subtly expelled Team Galactic from Shinnoh and pronounced themselves as the saviors of the region, Dawn and May are on the run, and Cynthia is too busy fending off Ghetsis's Hydreigon to do anything to help.
Blood In The Water has the biggest Near Villain Victory of them all. Effectively, Josh HAS won. Anna and Siobhan have been stalled by fighting Franz, who is attempting to kill them with his Lugia. Skyla is being deterred by a brainwashed Rico. Giovanni is attacking Mewtwo with Genesect. Josh himself has beaten all of Haleigh's Pokemon and forced Arceus to intervene, pissing it off enough to use Judgment and level the island, exactly what he wanted to happen. Arceus is pulled back into its own dimension thanks to Josh's Olympus Mons, and there is no way to win. But then Giratina pulls a Heel-Face Turn and sides with Haleigh, forcing it and Haleigh to engage Josh and his Rayquaza in an aerial battle above the ruined city.
Turnabout Storm: Part 4/4 sees Phoenix Wright completely out of evidence and witnesses that might exonerate Rainbow Dash. With no options left to the defense, the Judge delivers his verdict. OBJECTION!Fluttershy appears on the stand after realizing that she has new testimony based on evidence that had been presented earlier that day; evidence that leads to the extension of the trial, a new pony of interest being brought in for questioning, and pushing the series' conclusion to Part 5/4.
In Turtles Forever, 2003 Shredder nearly manages to kill the Original Comic Turtles, nearly destroying every single universe, until he's done in by Exploding Throwing Stars and really bad timing by Bebop and Rocksteady, that's right, the 2003 Shredder was killed by Bebop And Rocksteady.
Mother Gothel has two instances in Tangled. After manipulating Rapunzel into thinking Flynn abandoned her, she had her ready to willingly remain in seclusion forever. And later when Flynn comes to the rescue, she stabs him and Rapunzel is again ready to remain her wiling prisoner if she will let her heal Flynn.
Lord Shen in Kung Fu Panda 2 was able to successfully take over Gongmen City, build up an arsenal of cannons, and capture the Furious Five, also seemingly killing Po in the process. He's in the middle of riding out on his fleet to conquer all of China when Po comes back to stop him and even then he needs to pull out an Eleventh Hour Super Power to do so.
Also done masterfully in the new Star Trek 2009, where the Ax-Crazy Romulan ship nukes one planet, wipes out two fleets, and actually arrives in orbit over San Francisco and starts drilling not even 300 feet from the Golden Gate Bridge before the Big Damn Heroes moment.
In Star Trek: First Contact, the Borg have taken over most of the Enterprise-E and are about to destroy Zephram Cochrane's warp spacecraft the Phoenix, preventing first contact with the Vulcans, before Data reveals himself as a Reverse Mole to the Borg.
Probably one of the best-known examples is in A New Hope. The Death Star is about to blow up Yavin IV and the Rebel Alliance with it, their X-wing squad sent to destroy it have all been eliminated except for Luke Skywalker, who at the moment is about to be shot down by Darth Vader, when the Millennium Falcon appears out of nowhere, knocking Vader's TIE fighter into space and allowing Luke to fire the shot to blow it up.
The Battle of Endor in Return of the Jedi looked bleak for the Rebels for a while: Han and Leia were pinned down outside the shield bunker, unable to get in; the Rebel fleet was outgunned by the Imperial fleet, on top of which, the Death Star was more operational than advertised; and Luke, watching the fleet struggle, had just given in to his anger and tried to kill Palpatine, only to be stopped by Vader... The Death Star II was clearly just about to obliterate the Endor moon right before it exploded, since it had been rotated out of position to face the moon. If Lando hadn't destroyed the reactor when he did, the Endor system would be filled with barbecued Ewoks . . .
The Dark Knight. Everything is at the brink of chaos and oblivion before the Joker's nihilistic dreams are proven wrong, and Harvey Dent is stopped just in time only for Batman to make a pretty hefty personal sacrifice to keep his legacy intact.
Its follow up, The Dark Knight Rises, takes this a step further. Bane beats Batman and heavily injures him, flies him halfway the world to let him rot in a underground prison. Then takes over Gotham and turns it into a police state, likewise revealing the secret behind Harvey's death. The city nearly tears itself apart in the ensuring chaos which is just a waiting period so Wayne's energy reactor, now turned into an atomic bomb, can slowly overload. On the day they're meant to activate it, Bruce escapes his imprisonment just in time to help Gordan and the rallied remaining police mount war against Bane's forces. And even when Batman gains the upper hand. The last minute reveal of Talia Al Ghul tips the scales once again, leading to a chase through the city to stop the reactor and Bruce seemingly sacrificing his life to save Gotham.
In Oz: The Great and Powerful, the titular character's balloon is shot down by a Wicked Witch and goes down in flames. Then Oz reveals to his friends that he faked his death and convinces the witches (and the people of Oz) that his death made him even more powerful.
In The Terminator, the Terminator comes insanely close to murdering Sarah Connor in the Tech Noir club and accomplishing SkyNet's mission. He scours the club, and when he finally spots Sarah, the scene shifts to slow-mo with a droning metallic theme in the background. He calmly walks over and targets his gun's laser sight directly at her head, as Kyle grabs his shotgun from across the room and frantically tries to get the other people out of the way. The Terminator is less than a second from blowing her brains all over the floor when Kyle blasts him.
In The Avengers, Loki's Chitauri hordes have almost completely overwhelmed the Avengers. The Security Council, invoking this trope, decide to write New York off and launch a nuclear strike with the intent to wipe out the Chitauri, and the Avengers, and the millions of innocent civilians. The heroics of Mr. Anthony Stark negate the need for such drastic measures.
At the end of All Is Lost, the man sets fire to his raft in an attempt to hail a passing ship. He jumps in the water, and, realising he has just burned his last lifeline, gives himself up to the sea. As he starts to sink, he looks up, and sees a small boat coming to rescue him.
At the end of Scream 4 it seems like Jill's plan of recreating the Woodsburo murders - using the logic behind movie remakes - and replacing Sidney as the Final Girl will work. Then Jill makes a mistake when she tells Gale about their matching arm injury, which couldn't be possible unless Jill was the Ghostface that attacked her at the party. This leads to Jill dying at the hands of Sidney who she thought was dead.
The Last Crusade: First, Donovan thinks he’s found the grail when he enters its secret chamber. However, Elsa hands him a gaudy cup and he drinks from it, assuming he’ll become immortal, but he ages to death instead. Afterward, Elsa takes the grail within yards of the temple’s exit, but sets off a self-destruct sequence by stepping on the forbidden seal. In a Take My Hand scenario, she reaches for the grail below as she hangs onto Indy over a chasm. Her hand can nearly grasp it, which encourages her to keep trying despite the danger. Right as she’s about to grab it, her other hand slips from Indy’s hold and she falls to her death.
The Raiders of the Lost Ark: Indiana Jones arrives on the Nazi-controlled island and finds The Ark. The Nazis capture him and hold him and Marian prisoner while they open it up. This turns out to be a bad idea on their part, due to God hating the Nazis. The angels that come out of the Ark soon attack everyone except Indy and Marian. All the Nazis on the island are killed and Indy and Marian are freed.
In Neighbors, Teddy almost manages to get the cops to leave his party at the end of the film. Luckily, several developments allow his plan to fail.
Happens twice in Rush Hour 2: Chief Inspector Lee and Carter are both captured by Ricky Tan's right-hand woman, Hu Li. Just as she's about to kill the both of them, undercover agent Isabella Molina interferes and spares their life. Later in the film, Lee is captured again and is about to be tortured and killed by Hu Li but is yet again saved by Isabella Molina who reveals her identity as a U.S.S. secret service agent and attempts to arrest Hu Li.
In both the past and the future in X-Men: Days of Future Past. Magneto almost succeeds at eliminating American leadership and ushering in an era of mutant tyranny backed by the reprogrammed Sentinels, and the Sentinels almost succeed in eliminating the last of the X-Men.
J. R. R. Tolkien not only loved this trope (it appears throughout his books), he also proposed the term "eucatastrophe" for it and identified it as the typical ending of his definition of fairy stories in his essay "On Fairy-Stories". He also pointed out that a lot of beloved stories that don't fit into the fairy-tale category have a similar structure—like the central dogma of Christianity, which is about God Himself being killed, and then coming Back from the Dead. Some examples of it in his own work:
The Silmarillion: The final overthrow of Morgoth by the Valar, in response to the plea of Eärendil and Elwing.
The Hobbit: The Battle of Five Armies, saved by the arrival of the Eagles.
The Battle of the Pelennor Fields, saved by Aragorn's arrival at Minas Tirith.
The Battle at the Black Gate - in which most of the main characters expected to die in an attempt to give Frodo a chance - is not the primary eucatastrophe. The real one is Frodo failing at the end of his quest and, in a wonderful twist of fate, Gollum destroying the Ring, which turns everything around by killing Sauron, which also confuses his armies, which allows Aragorn & co to win.
In The Hound of the D'Urbervilles, Moran and Moriarty are actually on the back foot in the final story, as Moriarty is neglecting running his Firm to defeat his enemy, Mabuse. He does so, by manipulating Sherlock Holmes to find Mabuse. The plan then is for M&M to kill Holmes, return to London and get back to business, with none who can really oppose Moriarty. But Moran, who has been consistently treated poorly by Moriarty, feels that Moriarty would be fine seeing him go to jail to get on with his evil maths. Put up to it by Irene Adler, more or less, Moran shoots Moriarty, and the rest of Holmes canon (Holmes' near death, Moran's arrest) play out as usual.
Most obviously in Deathly Hallows: everyone believes Harry is dead. Neville has just tried to defy Voldemort, and is getting tortured with a burning Sorting Hat. No one else dares to stand up to Voldemort, who is blockading the school with his Death Eaters. A lot of good guys are dead or wounded. Then the centaurs attack, Neville breaks free and slices Nagini in half, and Harry reveals himself to be Not Quite Dead and zaps Voldemort.
A Song of Ice and Fire sees a strange variation in A Clash Of Kings, with Stannis's forces being at the gates of King's Landing and looking for all the world like they'll take the city and end a lot of the political conflict of the story before Lord Tywin unexpectedly returns, smashing his host in a surprise attack. The strange thing is that Stannis is the closest thing to a 'good guy' in the situation, although it's definitely not a total inversion due to the series's notorious Grey and Grey Morality and Black and Grey Morality.
The Lannisters themselves also get this. While it all seems that they have won the war, with most of their opponents now removed, and their rise to power opposed. They soon start tearing each other apart as they hate each other more than their foes. The result leaves Tywin dead, and Tyrion on the run, without the two of them to keep their reign together, Cersei starts running things to the ground when she becomes queen regent. Everything the Lannisters have fought for through, scheming, backstabbing and manipulation slowly crumbles as the whole realm is now against them, and the ones who are competent enough to hold it together are now gone.
In Warrior Cats, Scourge kills Firestar, and is about to defeat LionClan when Firestar, who is Only Mostly Dead, is revived by StarClan, to kill Scourge. This is because Firestar was given nine lives. However, there was still an off-chance that he would have died, given that Scourge killed the previous Big Bad, who also had nine lives, with one stroke.
The Yeerks are always on the edge of victory throughout the Animorphs series.
In the Mistborn trilogy, Ruin very nearly manages to destroy the world before Vin becomes a god, and then kills him via Taking You with Me. Even so, the world would probably still have effectively died if Sazed hadn't taken the powers of both Ruin and Preservation, and fixed everything.
The Inheritance Cycle begins with King Galbotorix having all but extincted Dragons and their Riders, ruling his Kingdom absolutely, with only a few pockets of resistance on its outskirts. Eragon, a rider trains to beat him, barely manages to prevent being captured for 4 books, only because Galbotorix does not want to kill him, much less won't just fly out to fight him with his Eldritch Abomonation of s Dragon. When the final confrontation begins, he calmly reveals he knows every "secret" they do, proceeds to defeat every countermeasure they had against him so effortlessly. Besides having years of experience, power, swordsmanship, wards against damage over Eragon (which in this universe, almost locks victory in) , he also reveals he has knowledge of The Word, allowing him to control the concept of magic itself.
The Wheel of Time has this on a schedule. At the end of every Age, the Dragon fights the Dark One; if he wins, this trope; if he loses, even bigger catastrophe. However, it's possible that the Father of Lies was, well, lying about having won the battle in prior ages. Or it could be future ages and he just doesn't know the difference - the books make it pretty explicit that he's just outside of the Pattern and would be pretty alien to all sorts of its characteristics.
Innumerable ones in the books themselves. When the party splits up, there can be as many as several for each segment of the main characters per book. That can come out to a dozen or so of this trope.
Both the Aes Sedai and the Dark One try to convince the Dragon that the other side is this trope. Xanatos Speed Chess doesn't begin to describe it. The Dark One even explicitly says that the story is this trope, and it's been thousands of schemes for thousands of years in the making
The writers and producers of 24 have perfected this to such a degree that they should copyright this trope. The villains generally cause enough damage before they are defeated up to the point where the heroes simply won't get to celebrate.
Likewise, Star Trek is pretty adept at bringing our heroes to edge of disaster before they win the day.
The Borg in Star Trek: The Next Generation mop the floor with Starfleet, kidnap The Captain, and make it all the way to Earth (as in, they park in orbit right above the Atlantic Ocean), before the Enterprise stops them at the last minute.
So to, the Xindi superweapon in Star Trek: Enterprise is blown up moments before it was ready to deploy within miles of the Earth's surface.
Unlike the top two examples, the Dominion actually managed to fire shots on the Earth's surface, and succeeded in messing up the Golden Gate Bridge. Additionally, several shapeshifters made it to Earth and other Federation worlds, causing massive panic. For a moment, it really did seem that the Federation would meet its first defeat ever.
The best Buffy the Vampire Slayer example comes at the end of season four, wherein Adam is only defeated by Buffy coming up with a spell to tap mystical ancient powers that give her the power, knowledge, and skills of Giles, Xander and Willow.
The spell required that they be close by (no just popping a spell pill and rushing off to the enemy's lair) so they all had to infiltrate a fortified underground base safely, then successfully reach a room where they hopefully wouldn't be bothered by the rampaging monster hordes and then, even when the spell is activated, there's a) the possibility it won't work at all, b) the possibility it won't work as intended, c) the possibility of it not being reversible (effectively killing Giles, Xander and Willow while making Buffy almost a demigod, and the longer the spell is active, the higher than probability gets) and d) the (proven) possibility of bad side-effects. So, it was kind of a hail mary, not something anyone really wanted to do unless they had to.
Seriously awesome when Buffy uses Willow's power and Giles' knowledge to turn missiles into doves.
Another example comes during the final battle in season 7: Buffy and Robin Wood are both stabbed, The Slayers are being overwhelmed and killed by Turok Han, Spike and Willow are incapacitated, and Anya is killed.
Illyria of Angel suffered this on her return. Despite the best efforts of the heroes to stop her, she successfully reached the dimension hiding her invincible army... only to find that the army had been destroyed in the ages since she was sealed away.
The Series 4 finale for the new Doctor Who has Davros literally seconds away from finally removing all non-Dalek life from existence. The scene itself and the leadup is pretty dark.
In Series 3, the Master actually succeeds in ruling Earth for 12 months.
At the end of Series 5, existence is literally wiped out for a brief time, and is saved only by Amy's consciousness. And so far, the perpetrators (The Silence) have got off scot-free.
In the Back Story to Babylon 5, the Minbari succeeded in obliterating most of EarthForce and had arrived at Earth with the intent to completely eradicate all humanity. Their sudden decision to surrender to the humans that they very clearly had on the ropes was one of the biggest plot points throughout the series.
By the series finale of LOST, Smokey/Locke had successfully killed three of the six remaining candidates, managed to get the last ones to help him uncork the heart of the island, was about to escape on the Elizabeth boat with the island collapsing in his wake, and fatally stabbed Jack. He was going to deliver the killing blow and get off the rock when along came Kate...
This is common for Power Rangers as nearly every season has the Big Bad nearly winning despite the victories and upgrades that the rangers have gotten during the season. Though special mentions include...
Mighty Morphin' Power Rangers - Rita Repulsa destroys the Thunderzords and by extension the Rangers' powers. They would be able to wreak their havoc on the world had the Rangers not gone to Ninjor and gotten new ones.
Followed by the villains annhilating the Command Center and stealing the Zeo Crystal at the conclusion of the Alien Rangers mini-arc. However, by the start of Power Rangers Zeo, the Rangers are able to turn the tide by retrieving the Crystal (which Goldar & Rita had dropped while teleporting) and gaining new powers.
Power Rangersin Space - The various villains from the previous Ranger series team up with Dark Specter and mount simultaneous attacks across the galaxy. They succeed in subduing all the Rangers and their various allies. The only thing that prevented them from winning was a Heroic Sacrifice by Zordon. sob.
Power Rangers Lost Galaxy - After Trakeena's fusion with Deviot increased her evil, she launches a massive Sting winger attack on Terra Venture with all of the strapped with bombs. She succeeds in destroying 2 megazords and nearly wipes out the civilians evacuating the colony. The Rangers use the Astro Megaship to damage the Scorpion Stinger and it crashes on a nearby moon. However Trakeena isn't done yet. With the massive power boost from the cocoon, she is able to energize the ruins of Terra Venture and sends it on a collision course for the civilian colony on Miranoi. The Rangers try to defeat her, but to no avail. Leo uses his armor and fires a point blank shot at Trakeena, finally taking her down. But the colony is still in danger. Thankfully, the Galactabeasts are able to shift Terra Venture's trajectory away from the colony.
Power Rangers Wild Force - Viktor Adler manages to truly become Master Org and preforms a ceremony to make an Org Heart which makes him neigh unstoppable. He destroys the Ranger's Power Crystals which in turn destroys the Zoids, defeats and kills Animus, forces the Animarium back into the Earth and depowers the rangers before sending his vines to take over Earth. It's only due to the Rangers unwilling to give up that it summons the remaining animal crystals to their aid and turns things around.
Used magnificently in the Anthony Andrew's version of The Scarlet Pimpernel when Percy comes back from the "dead", having supposedly been executed by firing squad. The look on Chauvelin's face when he turns around and sees him standing there is absolutely priceless.
Percy: My good fellow, I would never dream of depriving you of your moment of triumph. Alas, a moment was all I could spare.
By the fifth season finale of Supernatural, Lucifer has hijacked Sam's body, and he and Michael are about to tear the world apart in the deathmatch of the century. Then Dean shows up in the lampada and his presence is enough for Sam to wrestle back control of his body and seal himself, Lucifer and Michael in an inescapable pit.
A frequent occurrence on Stargate SG-1. The best example is probably the season 8 episode "Threads". Anubis is mere moments from destroying all life in the galaxy and no one can stop him...until Oma Desala saves the day via Sealed Evil in a Duel.
The Ancient Bards song "Hope Dies Last" is about one of these.
In "Neverland" from Big Finish Doctor Who the Neverpeople come very close to piloting a Time Station containing an anti-time bomb onto Gallifrey, which will destroy the Web of Time. The Doctor only just stops them by materialising the TARDIS around the time station.
In the finale of series 2 of the New Eighth Doctor Adventures Morbius returns and takes away the Time Lord's power. He then rules an Empire for over ten years, conquering over ten thousand worlds including Earth. Thankfully the Time Lords are able to pull a Reset Button.
In the Grand Finale of the NEDA the Dalek Time Controller comes very close to activating a time engine that will send Earth through time and turn it into a plague planet which the Daleks will pilot through the Universe and use to infect worlds, having captured the Doctor, Susan and Alex, with Lucie in a Dalek Saucer which has been caught in a magna-clamp. Though he is stopped it take two heroic sacrifices, making this one of Doctor Who's biggest Downer Endings.
In Pokémon Live!, Giovanni's plan works completely, and he tries to kill Ash and Pikachu with Hyper Beam after they served their purpose in his plan. If not for Mewtwo's intervention, he would have won.
The plot of the Ace Combat series revolves around this. the player is an ace pilot that acts as a tipping point in the war during gameplay. Where as the cut scenes revolve around the ramifications of the player's actions.
Ace Attorney: Phoenix Wright can never go into a trial and win, he has to be getting his ass kicked until he comes to a point where everything seems hopeless. That's when he can turn things around. Possibly was the same for Mia Fey. In general, near the end of every case there's a moment where e.g. the prosecutor points out that you have no decisive evidence to prove the murderer's guilt, and as the murderer stands there gloating and mocking you, Phoenix manages to get a bright idea at the last minute, or someone bursts into the courtroom with a piece of vital evidence just before the judge announces his verdict, etc.
In the course of the series, Phoenix (deep breath): defends the sister of his mentor, apparently accused by the victim of the murder, successfully brings about the downfall of a man blackmailing half the legal system, defends a hated prosecutor accused of killing a man a few days before, then successfully defends the same man for a crime committed fifteen years ago by a different prosecutor who had never lost a case before, by correctly accusing the same perfect prosecutor, takes down a viciously corrupt chief of police while defending someone who had already confessed to the crime repeatedly and in detail, defended someone without his memory, defended his assistant from a crime that, circumstances show, could only have been committed by said assistant, successfully maneuvered a Manipulative Bastard into confessing to a crime while his assistant was held hostage to ensure said bastard's acquittal, defended someone already found guilty, and finally, successfully defended a woman he thought had tried to kill him because he was convinced of her innocence (oh, and the evidence is all against her, too). Lampshaded by the fact every case except one (and the series title in Japan), all have the word "Turnabout" in them, and how in the English versions he's named Phoenix for his tendency to "come back from the dead".
In The World Ends with You Kitanji has Neku at his mercy. His brilliant Evil Plan that he had spent the entire game setting up has come to fruition, leaving Neku alone and defenseless. The reapers summon a whole army of Noise and are about to erase Neku when the Spanner in the Works sets in.
Soul Nomad had a few when you were fighting the World Eaters, Raksha especially seemed unstoppable
In Dragon Quest IX, after you defeat the Big BadCorvus in battle, he says he will destroy the world anyways. Then his one true love, a mortal named Serena explains she didn't betray him, at which point he stops, invoking this trope.
Star Ocean: The Second Story also deserves this mention: At the end of Disc 1 you face the Big Bad for the fate of the world of Expel. You get trounced, Expel is destroyed (although returned to existence later) and you wake up on the Big Bad's home planet.
The 2 Custom Robo games use this at their seemingly invincible final bosses. The DS's version's example is a lot like the FF 4 one.
This also happens in main-series games. Notable is Super Mario Galaxy, where Bowser is minutes away from completing his plan when Mario arrives.
Ganondorf in The Legend of Zelda: Ocarina of Time scores a fairly impressive victory during the first arc of the game — he tricks the heroes into doing most of the work for him. He then kills the King, conquers Hyrule and reigns supreme for seven years, while the rightful heir to the throne has to change her gender cross dress in order to effectively hide from him, and The Hero is put in an enchanted sleep that will allow him to grow up sufficiently in order to put the kingdom back to rights.
In Twilight Princess, Zant and the Twilight took over all of Hyrule except for the backwater province that also happened to be Link's home, and then got beaten back into its hidey hole, only to be later defeated and left slumped in his throne while Link goes to rescue Zelda.
At one point in Super Smash Bros. Brawl, every single playable character (and Master Hand) is dead (well, trophyified). Then Dedede's timed badges go off...
Fate/Stay Night, Heavens Feel. First Saber is gone. Very gone. Then in quick succession, Archer dies, Berserker follows and Shirou loses an arm. Plus, Saber is Not Quite Dead... but that's not a good thing. Then Sakura is revealed to be the Shadow, plus Zouken Matou controls her. And Berserker is back, plus blind and insane... insaner. So many things go wrong that by the time you get to the end you're down to Tohsaka and Shirou. Tohsaka has a weapon she isn't sure will work and Shirou has severe brain damage plus a limited amount of times he can project before he'll die. Luckily, Sakura makes things a bit easier by killing True Assassin and Zouken for them.
Mortal Kombat 3: To break it down, Shao Khan revives his dead wife on Earthrealm, allowing him to step through the boundaries separating it from Outworld and claim her, thus forcing a merger of the two realms without the need of the eponymous tournament. Not only that, but he immediately steals the souls of everyone on Earth, and sends out extermination squads to take care of The Chosen Ones who had their souls spared. He barely avoided victory, due to his underestimating the power and tenacity of his foes.
Mortal Kombat 9 sees things get worse: Raiden's attempts to prevent Armageddon see the situation deteriorate until the only surviving Earthrealm warriors are Johnny Cage and Sonya Blade. The only reason Shao Khan's attempt to conquer the realm failed was because Raiden finally realized that the future message of "He must win" referred to Shao Khan: allowing him to conquer Earthrealm would force the Elder Gods into action.
Fallout: while you are hunting for the Master and the Vats, the mutant army is on the doorstep of Vault 13.
Fallout 2: by the time you get to the Oil Rig, the Enclave is ready to launch the modified FEV biotoxin into a jetstream which would completely depopulate North America.
Fallout 3: fortunately for the good guys, the Enclave doesn't know the code to activate Project Purity which results in the Brotherhood launching a desperate siege and pushing them out of there. However, the Enclave was about to use their Kill Sat on the Citadel afterwards so it counts as two.
New Vegas has this as a possible ending; depending on how thoroughly you complete sidequests and make friends with folks that have a lot of firepower, the ultimate battle for Hoover Dam is either an unbelievably harsh battle of attrition, or a hysterically drawn out Curb-Stomp Battle as all your allies come rushing in for one Big Damn Heroes moment after the other.
At the end of Halo 2 and the middle of Halo 3, the Halos were activated and charging, and just a few minutes from firing and killing all life in the galaxy just before the heroes could push the off switch.
The first Mass Effect game had you racing against time to stop Saren and Sovereign from opening the secret Mass Relay built into the Citadel to let the Reaper fleet through and begin the massacre of all sentient life in the galaxy.
However, it's clear that the invasion is still coming and Shepard's actions have, at most, merely delayed it. This is proved true in The Arrival when Shepard is forced to destroy a Mass Relay and an entire inhabited solar system to buy the Galaxy some time. It turns out this was only several months, as the invasion finally happens in Mass Effect 3.
Cerberus comes very close to pulling off this and a Team Rocket Wins in the third game, by going on the offensive and repeatedly hampering everyone's attempts to combat the Reapers effectively. Eventually the Alliance is forced to perform an all-out assault after they steal crucial information needed to finish the Crucible.
The second Air Gem test in the Fan Remake of King's Quest II. The canonical games glossed over this point, but the kingdom is in ruins, the hero's kids have been condemned to death, and the hero himself is close to breaking... then in walks the Big Bad offering a Deal with the Devil.
Canonical ones in the series: walking into the wedding hall in King's Quest VI to see "Cassima" enthusiastically declaring her intent to marry the Grand Vizier. And in King's Quest IV when Lolotte nastily declares that Rosella will have the Standard Hero Reward of marrying her grotesque "son" turns out he's just a prisoner, too, strips Rosella of all her possessions, and locks her up.
In the Space Quest series: Roger is captured by Vohaul in Space Quest 2, shrunken down to miniature size, and shoved in a jar while Vohaul readies the launch of his clone army of life insurance salesmen. In Space Quest 5, Roger is stranded on the bridge of the Goliath, surrounded by Pukoids, and the ship's heading for Confederation space, ready to spread The Corruption to all of known space. If you prepared for this, then WD-40 and Cliffy show up for a Big Damn Heroes moment. Space Quest 6 isn't as dramatic, but it is sad. After the Big Bad tried to kill Roger, Stellar shows up and pulls a Heroic Sacrifice. He can only bang on the door helplessly as she appears to succumb to the gas. Worse, Sharpei is going to get away with it because she is the wealthy and well-connected widow of a famous admiral while Roger and Stellar are "just" a janitor and soldier.
Pokémon had been slowly hedging in that direction for a while with the villains of Ruby/Sapphire/Emerald and Diamond/Pearl/Platinum coming ever closer to their goals. In Black and White, the bad guys got their legendary. They proceed to defeat the league champion, leaving them with the firepower and the moral authority to get the region to release their Pokémon. In their castle ( which has risen from the ground to surround the Elite Four headquarter, scientists are hacking into the Pokémon storage system, elevating them to global threat. And while N wishes to face you in a one on one battle first, the Sages are a little more pragmatic and intend to take you six on one and quite likely kill you before you make it that far. If you do, you still don't have, or don't know where to find, the opposite legendary, which might even the odds a little in that battle. You have the stone to awaken him, but no idea where or how to use it. Then your childhood friend Bianca rounds up the gym leaders of Unova who hold off the sages, and the stone you've been carrying all along ends up working at the last minute. The rest is up to you.
In Diamond and Pearl, Cyrus arguably comes even closer than Ghetsis. Even if N had beaten the player character, that wouldn't necessarily have handed him the region since there are plenty of other strong trainers about (particularly Cynthia) and there's the very real possibility that N would have worked out what was going on and stopped Ghetsis personally. Throughout Diamond, Pearl and Platinum, you fail to stop any of Galactic's Commanders or Cyrus even once, up to and including when you reach Spear Pillar, where only a major Deus Ex Machina stops Cyrus' total victory.
To take the most telling example, Kane in Command & Conquer: Tiberian Sun was only three hours from launching his World Altering Missle when Mike McNeill arrived to the battlefield. Said missle would have converted all life on the planet into Tiberium-based life.
In the meaningfully-named Allied mission "Last Chance" in Command & Conquer: Red Alert 2, the Soviets almost succeed in using a Psychic Amplifier to mass mind control the entire United States.
In the opening of Yuri's Revenge, Yuri activates his Psychic Dominator network, successfully mind controlling most of the planet. It's only due to one of them getting temporarily damaged that a time travel device the Allies built can be activated to undo Yuri's plan.
On RuneScape Lucien has completed the Ritual of Rejuvenation, sacrificing the weakest member of his species to recharge the powers of the rest, and he also has possession of the Stone of Jas, in his attempt to become A God Am I. Them the Dragonkin kill him.
In No More Heroes, Jeane managed to shove her fist inside of Travis' heart and need only rip it out. Then enters Shinobu, paying you back for sparing her life, who then proceeds to cut the arm off as Travis goes for the finish.
Ōkami eventually gets rather dire as Yami has Ammy near death with her powers cut off and no help coming, but Issun went through with his role of being the person who reminds the world of Ammy, allowing her to regain much of her lost power.
In The King of Fighters '94, if Kyo Kusanagi didn't assume the worst when he saw his father unconscious after Rugal beat him to almost death, he would have never gone into an Unstoppable Rage-induced Heroic Second Wind and Rugal would have won. Kyo gets lucky for a second time in the next game when Rugal's own power destroys him.
In Hyperdimension Neptunia V, as early as Chapter 3, Mr. Badd could have won against the three CPU goddesses without him having to lift a finger. The only flaw in his plan is an unknown fourth CPU goddess who was present at that time (and to be fair, Vert WAS being covert at that time, trying to observe Lowee's CPU).
Ghost Trick is about as damn near close as a story can come. To wit: almost everyone is trapped underwater in the penultimate chapter. The submarine Lynne, Kamila, Sissel, and Missile's ghost are on is unsalvageable. Detective Jowd is elsewhere, dead in a room drifting to the bottom of the ocean. Commander Sith has plucked the Temisk fragment from Yomiel's body and is on his way back to his homeland. The only way the protagonists end up standing a chance is by launching Sissel and Missile's ghosts to Jowd's location via torpedo, rewinding back to Jowd's death, then rewinding back to Yomiel's "death" in Temisk Park ten years ago to finally Set Right What Once Was Wrong. Essentially the timeline that you left behind when Sissel was launched on the torpedo is completely doomed and you only save everyone by rewriting history.
Deliberately invoked in The Order of the Stick by Tarquin. He's a Genre Savvy believer in the Theory of Narrative Causality. He thus takes heart in the fact that while The Good Guys Always Win (maybe), they tend to win against a bad guy who was so powerful and reigned for so long no one thought he could be beaten. And Tarquin is fine with being defeated in the end in exchange for being an all powerful despot for a few decades before it happens. So he's already won, and gets to keep on winning and getting more powerful unless/until somebody beats him.
On top of that, his Good-aligned son is the most likely to take him down, which plays right into his plan to keep on winning by becoming part of a legendary struggle of good vs. evil, so he can inspire generations of new villains with his example of how to live the good life.
In Aelan mythology from Ustal Naror islands, end of era of earth, when concretes and earth will start to grow in power, but the oldest stone will finally manage to destroy it, will be an eucatastrophe.
Worse, Shego LEFT THE FREAKIN' BACKPACK with ALL of the gadgets IN THAT VERY ROOM!
The Alien Invasion in the Grand Finale probably counts as well. It may actually be the closest in the series the world came to ending.
Nox, the Big Bad from Wakfu, seeks to travel back in time to save the family he had failed 200 years prior to the show, an act which would also undo all of the myriad of atrocities he had committed up until that point in the pursuit of that goal. Despite the heroes' efforts he successfully drains the Sadida's Tree of Life, resulting in the death of their entire race, in a bid to power an ancient artifact that he believes will allow him to turn back time. In the final battle between him and The Hero, Yugo, it looks for a moment as if Yugo is going to win. However, Nox uses a momentary distraction to kill (well, maybe knock out, since he does the same thing to Yugo's dad in the second episode, and he lived) Yugo. With The Hero dead, Nox uses all the energy he had collected over the last 200 years to travel back in time. Unfortunately for Nox, that is barely even enough to travel back in time 20 minutes. In a bit of a twist the ending might actually have been happier if it had been a complete villain victory instead of merely a Near Villain Victory.
This happens twice in Avatar: The Last Airbender : the Fire Nation ultimately wins the war at the end of the second season, forcing Aang and his friends into hiding on enemy territory. Later in season 3, the few remaining pockets of resistance unite for a surprise counter-attack on the Fire Nation capital; it fails, costing the Avatar most of his remaining allies.
Frankly,the whole premise of the show, the Fire Nation have won the war at the beginning,it isn't until Aang is rescued from the iceberg that any credible threat arrives.
From the Sequel SeriesLegend Of Korra, Amon comes within seconds of completing his plan, having successfully robbed Korra of her powers and taken over Republic City. The only reasons he fails are beyond his control; namely Korra suddenly being able to airbend and his own survival instincts.
Played with on Reboot: Megabyte takes advantage of the chaos during the Web invasion to get rid of Bob and cripple Mainframe's defense forces, but he's then imprisoned by Enzo at the start of the third season. Because the series follows Enzo's adventures in the Games after that, we don't know what happens to Mainframe until he rescues Bob and finds a way home - only to find that Megabyte escaped and conquered the city a long time ago.
Galaxy Rangers episode "Shoot Out." The Queen has three Rangers in chains, displaying them like a trophy. The fourth is competing for his life in a Blood Sport where the Queen's new champion has shot and wounded him. The animation where she's on her feet cheering while her captives look on in dismay is wonderfully done.
Transformers Cybertron uses this. Galvatron has the MacGuffins in his hands. He knocks out Primus himself, and is on the verge of achieving his desire of godhood. The universe is minutes from being consumed by the Unicron Singularity, leaving Galvatron to remake things in his own image. The Autobot leaders - Optimus Prime, Override, Scourge, Evac, and Metroplex - manage to kick his aft by combining their Cyber Key attacks (leading to him having the following Oh Crap moment: "Uh-oh.", which works beautifully as delivered by David Kaye). But he's not through yet. Galvatron, in a last act of spite, pitches the Omega Lock and Cyber Planet Keys into the Unicron Singularity. If he can't win, nobody will. But even this fails. Override, Scourge, Evac, and Metroplex recover the keys, and Optimus Prime snatches the lock back from the jaws of the event horizon. The lock and keys couple to Primus' body, fully reconnecting his spark and bringing him back to full power. He uses the massive starship Ark to channel his power as a Wave Motion Gun, firing it at the Unicron Singularity. The unnatural black hole of doom shudders, contorts, and disappears. His work done for now, Primus transforms back into Cybertron. But not as it had been, chewed up by the hell of war. It is reborn as a paradise for humans and Transformers alike. Just goes to show, the closer to ultimate victory you are, the harder you fall when it's snatched away.
But there's still more. In the next episode, it's the Final Battle. Optimus Prime versus Galvatron, to the death. Galvatron has Optimus knocked flat on the ground, face in the dirt of one of Cybertron's moons. As he brings his sword down for the killing blow, Vector Prime uses the planet map (his last physical link to the linear universe) to block Galvatron's blade as well as give Optimus Prime his sword Rhisling. Optimus uses it, combined with the power of the Matrix of Leadership, to skewer Galvatron, killing him. Galvatron gives his fitting Famous Last WordsFinal Speech: "I still function... you haven't... won... not while my... spark... still burns... ha ha ha ha ha ha..." before crumbling to ashes that are swept away by the lunar winds.
Beast Wars Megatron has been just a hair away from victory three times. the first time he nearly erased the Maximals from existance by killing Optimus Prime four million years before he woke up. The second was when he found the repaired Nemesis and tried to use it to kill the Autobots still offline in the Ark. The third time he absorbed nearly all the sparks on Cybertron, became a god, and tried to remake Cybertron in his own image.
Happened alot in Totally Spies!, such as the second episode, "The New Jerry", with the Spies trapped in a space capsule and Tim Scam firing on the Earth with the Evapo-Blaster.
Happens again in the Season 2 finale. The Changeling Queen has destroyed the barrier protecting Canterlot, unleashed her hordes upon the city to feed off the love of all the ponies, and has even defeated Celestia in a straight-up fight by tapping into Shining Armor's love for Cadence. Even worse, the Mane 6 fail to reach the Elements of Harmony in time, and are captured by the thousands of changelings that now storm the city. Unfortunately for the queen, she forgot that Cadence and Shining Armor are still in the room, and that Cadence's magic is the ability to make ponies love each other. The result is Shining Armor getting a massive injection of the Power of Love, which gives him enough power to reset the barrier and blast all of the changelings out of Canterlot once and for all.
The Season 3 two parter also has this happen, with a twist. King Sombra's near victory is the result of his actions taken before the story even starts. Cadence's magic gives out, causing the barrier keeping Sombra locked out to fail and Sombra himself to enter the Crystal Empire. Twilight ends up trapped by a crystal barrier, which also begins to corrupt the Empire from the inside and prevents her from getting the Crystal Heart where it needs to be defeat Sombra. Spike manages to get the Crystal Heart and try to get it to where it can defeat Sombra, but Sombra attacks, coming within a few inches of capturing or possibly killing him before Shining Armor throws Cadence like a javelin to catch Spike and the Heart, allowing them to power it up and kill King Sombra.
Hell, it happened in the very first episode of the very first season. Nightmare Moon popped up, carried out her plan, removed her sister, set her traps, destroyed the Elements of Harmony...except that last step turned out to have failed.
Yet again, (noticing a trend here?) in the season 4 finale, Tirek nearly wins having drained magic from all Earth ponies, unicorn ponies, pegasus ponies, and even Discord (whom Tirek had deceived into joining his side); nobody was powerful enough to stop Tirek. It was Discord's Heel Realization and giving Princess Twilight his medallion from Tirek that allowed Twilight to unlock the power to stop Tirek, imprison him once more, and restore everything back to normal.
At the end of the SpongeBob SquarePants episode "Frozen Face-Off" this happens to Plankton, then the snow monster confuses him for a jellybean.
Lord Darkar from Winx Club was seconds from obtaining the power of the Realix and securing his victory when Bloom managed to break free from his control and hijacked the Realix power.
Dick Dastardly appeared to have won the race in the Wacky Races episode "Creepy Trip To Lemon Twist," until the judges ask to see a slow-motion replay. It shows Dastardly extending the nose of his car ahead of the other racers. He is disqualified and the race awarded to Penelope Pitstop.
In Turtles Forever, the Utrom Shredder was the closest that he (or any other Shredder in the history of the entire franchise) had gotten to destroying the turtles. He was done in by exploding ninja stars, his ego, and Bebop and Rocksteady.