BRUSSELS — European Union leaders on Thursday agreed to extend the deadline for Britain’s looming exit from the bloc in order to give Prime Minister Theresa May and the British Parliament more time to get their act together.

Thursday’s agreement effectively averted the possibility of a disorderly and possibly chaotic departure by Britain on March 29. Yet that still remains a possibility just a few weeks later.

After hours of difficult and sometimes passionate talks, the leaders decided that Britain’s exit date will be pushed back to May 22 if next week Mrs. May can persuade lawmakers in Parliament to accept her plan for leaving the bloc, which they have already rejected overwhelmingly, not once but twice.

If she cannot persuade lawmakers to accept her plan, Mrs. May will get a shorter delay in exiting the European Union — until April 12. But Britain could stay in the bloc longer if it decides it needs more time for a more fundamental rethink of Brexit, as the process is known.