From 1685 to 1688, he was active not only as Secretary of the Admiralty, but also as MP for Harwich. He had been elected MP for Sandwich, but this election was contested and he immediately withdrew to Harwich. When James fled the country at the end of 1688, Pepys's career also came to an end. In January 1689, he was defeated in the parliamentary election at Harwich; in February, one week after the accession of William III and Mary II, he resigned his secretaryship.