Foreclosure doesn't happen overnight. Typically, it'll be a few months before the lender will start the foreclosure process, as you miss payments. During this time, it's best to consider all of your options for the best possible financial outcome.
One of those options is to use bankruptcy, which can buy you even more time by temporarily halting the foreclosure process.
Essentially, when you declare bankruptcy, the court puts an automatic stay on everything you owe. The lenders can't come to collect until you go through the entire bankruptcy process. They have to wait and see what the outcome will be, as it drastically influences your debt. This automatic stay also applies to your mortgage, so the foreclosure must wait.
Wondering how long you'll get? It depends, as bankruptcy cases aren't exactly the same for everyone. Generally speaking, though, you're looking at anywhere from three to four months.
You can then use that time to get your finances in order. You may even be able to use bankruptcy to rearrange what you owe into a payment plan -- Chapter 13 -- so that you can afford the home again. Even if you can't, you get more time to look into your options and plan for the future.
There are exceptions to this rule, however. For instance, the lender may be able to ask the court to lift the automatic stay in certain situations. As such, it's very important for you to know everything you can about the bankruptcy process, what types of bankruptcy you're eligible for, and how you should proceed. Don't panic when facing bankruptcy; just take the time to consider all of your options and all possible outcomes.
Source: Bankrate, "File bankruptcy to stall foreclosure?," Justin Harelik, accessed Jan. 26, 2017