Djokovic, who hadn't lost a set in his first three matches, dropped one to mercurial Roberto Bautista Agut but prevailed in four sets 6-3, 4-6, 6-4, 6-3.
"It was a great match tonight," Djokovic said after the win, a display of sometimes electric shot-making by both men. "I had a chance to close him out, and I didn't capitalize, so he turned it around and make it tough. Credit to him."
The win put Djokovic into the quarterfinals of a Grand Slam for the 26th consecutive time, just one behind Jimmy Connors and third behind Federer's record 36.
The match lasted just over three hours, and Djokovic appeared to have it well under control when he led by a set and a break, with points to add an insurance break. But Bautista Agut, the No. 28 seed, survived the seven-minute service game to hold and remain within striking distance at 3-4.
Bautista Agut's game then took a quantum leap, as he began to strike blazing winners, mostly off the forehand wing that Djokovic stubbornly kept attacking. Bautista Agut hit 22 forehand winners in the match, five more than Djokovic.
"I think there were several moments in which I managed to rattle him, making him uncomfortable on the court," Bautista Agut said.
By the start of the third set, many were comparing the Bautista Agut's surge with the astonishing performance Fabio Fognini produced in his upset of Rafael Nadal two nights earlier.
The effort took a heavy toll, though, and Bautista Agut's engine began to sputter early in the third set.
"Obviously, at that moment it wasn't easy, but I managed to regroup," Djokovicsaid, "and use the experience of facing these particular situations before in my life, knowing what to do next."
Djokovic broke him early and coasted through the set. Bautista Agut fell behind early in the fourth set. He rallied again to reach 2-all, but Djokovic hit another gear and rolled to victory.
Information from The Associated Press was used in this report.
Djokovic advances to quarterfinals
Top-seeded Novak Djokovic advances to the quarterfinals after beating No. 23 Roberto Bautista Agut (6-3, 4-6, 6-4, 6-3).
Djoker talks win over Bautista Agut
Novak Djokovic talks to ESPN tennis analyst Brad Gilbert about his win over Roberto Bautista Agut in the fourth round at the US Open.