On a Centre Court, with an atmosphere that felt at times more akin to football than tennis, Djokovic won 7-6 (7-5) 1-6 7-6 (7-4) 4-6 13-12 (7-3).
As the clock ticked to four hours 57 minutes, Federer hit a ball high to hand the Serb victory.
The world number one has won 16 Grand Slams - and four of the last five.
"It's quite unreal," Djokovic said after winning his fifth Wimbledon title.
Federer, who at 37 was chasing a record-equalling ninth Wimbledon singles title, added: "It was a great match, it was long, it had everything. Novak, congratulations, man, that was crazy."
The Swiss had been seeking to become the oldest Grand Slam champion of the Open era but instead found himself part of a different record as the match time surpassed Wimbledon's longest final - the four hours 48 minutes of play in 2008 as he lost to Rafael Nadal.