For much of its time Kabul was independent until it became part of the Durrani Empire in 1747. During the First Anglo-Afghan War in 1839, the British army invaded the area but withdrew in 1842, although thousands of them were killed during a surprise ambush on their way to Jalalabad. In retaliation another British force partly burned Kabul before retreating back to British India. The British again occupied the city during the Second Anglo-Afghan War in 1879, after their resident staff were massacred there, but withdrew about a year later when they installed Emir.