And we say in the Gemara (at the beginning of Bava Batra) that this prohibition only applies when there is no structural flaw in the old one. But when we see a structural flaw in it—it is permitted in any case. That is to say: specifically when the old one is still strong and there is no concern of damage, then it is forbidden to demolish it until they build the new one. But if its foundations have crumbled, or its walls are leaning toward falling, or there is danger in the roof or in the beams—they demolish it immediately. They only begin to build the new one by day and by night if possible, and they hasten its construction so that it is not drawn out for long. And in the Gemara there, it is brought regarding an incident of this sort, that one of the sages brought his bed in there so that they would hasten its construction. (And see Magen Avraham subsection 4, that the intention is near the synagogue, see there. And it is not compelling, as the Eliyah Rabbah wrote in subsection 4, that for the need of the synagogue—it is even permitted in the synagogue. And also what he wrote in subsection 5 against the Bach follows his own reasoning in subsection 1. And it is not so, as I wrote in section 2. And also the intention of the Bach is not as he wrote, but rather when the person stands in the middle of the building. And the Machatzit HaShekel already noted this, see there.)
ואמרינן בגמרא (ריש בבא בתרא) דאיסור זה אינו אלא כשאין בו תיוהא בהישן. אבל כי חזינן בו תיוהא – בכל עניין שרי. כלומר: דדווקא כשישן הוא חזק עדיין ואין בו חשש נזק, דאז אסור לסותרו עד שיבנו החדש. אבל אם חרבו יסודותיו, או נטו כתליו ליפול, או שיש סכנה בהגג או בהקורות – סותרין אותו מיד. רק מתחילין לבנות החדש ביום ובלילה אם אפשר, וממהרין בבניינו שלא יתמשך הרבה. ובגמרא שם איתא במעשה בכהאי גוונא, שהכניס אחד מן החכמים מיטתו לשם כדי שימהרו בבניינו. (ועיין מגן אברהם סעיף קטן ד' דהכוונה סמוך לבית הכנסת, עיין שם. ואינו מוכרח, כמו שכתב האליה רבה סעיף קטן ד' דלצורך בית הכנסת – הא גם בבית הכנסת מותר. וגם מה שכתב בסעיף קטן ה' נגד הב"ח הולך לשיטתו בסעיף קטן א'. ואינו כן כמו שכתבתי בסעיף ב'. וגם כוונת הב"ח אינו כמו שכתב אלא כשהאדם עומד באמצע הבניין. וכבר העיר בזה המחצית השקל, עיין שם.)