European leaders agreed with Britain on Thursday to delay Brexit by up to six months, saving the continent from what could have been a chaotic no-deal departure at the end of the week.

The deal struck during late night talks in Brussels means that, if London remains in the EU after May 22, British voters will have to take part in European elections — or crash out on June 1.

Prime Minister Theresa May said she would now keep working to get her withdrawal agreement approved by parliament to ensure an orderly split, saying her goal was to leave “as soon as possible”.

She will address the House of Commons on Thursday before her officials meet for further talks with the main opposition Labour party, to try to find a way through the political deadlock.

The other 27 EU leaders met without May over dinner to thrash out what European Council president Donald Tusk called “a flexible extension until 31 October”, before she returned to seal the deal.

Tusk had proposed a year-long delay, but said: “It’s still enough to find the best possible solution. Please do not waste this time.”

He suggested May’s government now had time to ratify the deal agreed with EU leaders in November, to rethink its approach or to stop the entire Brexit process.

The summit conclusions say Britain must hold European elections set for May 23 or if “the United Kingdom fails to live up to this obligation, the withdrawal will take place on 1 June 2019”.

Britain has already started planning for the polls, but May told reporters that she hoped she could still get her deal agreed by May 22 and avoid taking part.

“The EU have agreed that the extension can be terminated when the Withdrawal Agreement has been ratified,” she said.

The summit was more tense than expected, with France’s President Emmanuel Macron the strongest voice opposing a long extension as the talks stretched from early evening to early Thursday morning.

With backing from Belgium, Austria and some smaller EU states, he pushed to limit the delay to only few weeks and demanded guarantees that London would not interfere in EU business during that time.

But most leaders backed the longer plan, including German Chancellor Angela Merkel, and the French had to settle a review of the delay at a pre-planned EU summit on June 20 and 21.

Macron said afterwards this was the “best possible compromise”, which “made it possible to preserve the unity” of the other 27 EU states.

“The October 31 deadline protects us” because it is “a key date, before the installation of a new European Commission”, he said.

Without a postponement, Britain would have ended its 46-year membership of the EU at midnight (2200 GMT) on Friday with no deal, risking economic chaos on both sides of the Channel.