Pakistan resumed after tea in Rawalpindi requiring just 86 more runs to win with five wickets remaining, but England fought back to secure an unlikely victory as the sun began to set over a packed stadium.
Brendon McCullum and Ben Stokes did not deviate from their attacking and unconventional approach with both bat and ball and were rewarded with a first England away win in 12 Tests.
There was a lengthy rearguard effort from Pakistan for the final wicket, with all players surrounding the bat, but it was eventually broken when Jack Leach trapped Naseem Shah lbw - the first wicket to fall to spin in the final innings.
The tourists had looked to be toiling away without reward with only three seamers on a pitch where the fast-bowling option looked the most likely to provide a breakthrough, but Ollie Robinson claimed two quick wickets in his first Test in the subcontinent to change the momentum of the match.
The England swing bowler had been dropped from the squad following a disappointing winter in Australia and the West Indies and concerns over his fitness but has bounced back in his first Test overseas since.
Facing Robinson, Agha Salman had been given not out on the field following an emphatic England lbw appeal, but the visitors' decision to review proved the right one and he had to depart for 30.
The very next ball after Salman's wicket, the ball brushed the off stump behind Azhar Ali but did not dislodge the bails.
The top-order batter had retired hurt on the evening of day three with a blow to the finger, resumed and had looked comfortable at the crease before he was caught by Joe Root at leg slip off Robinson, the seam bowler's second in two overs.
Ali had made 40, but his wicket left Pakistan needing 83 runs to win with three wickets left, with defence becoming the order of the day as the batters instead looked to hold out for as long as the light remained.
England had more than an hour to bowl at the tail, which contained three debutants, but the game went down to the wire with the sun already beginning to set over the stands.
With the weight of his experience behind him, 40-year-old James Anderson put England on the brink of victory when Zahid Mahmood just tickled the ball behind with wicketkeeper Ollie Pope taking a diving leg-side catch.
Anderson followed it up almost immediately with another, trapping Haris Rauf lbw for a duck. That decision was upheld despite a review, as was the final wicket of Shah.
England's daring declaration at tea on day four had set up a thrilling contest on the final day, tempting Pakistan into going for victory with just 343 runs needed to win on a very flat deck.
The tourists had hit 264 runs in just 35.5 overs in their second innings at a run rate of more than 7.5 and had left the game poised with all results possible going into an exciting final session, as the match broke the record for the most runs ever scored in a five-day Test.