A lot of programmers think of programming as a craft. Me included. But there is a thing in other crafts that I miss in the programming world. Journeyman years. If you aren't aware of that concept, it basically means that after you are finished with learning the basic skill of your craft, you had to go on a journey for a few years to improve your skills with new techniques and styles used in other cities or countries. Granted, there are not that many who still do this and the rules behind most of those organizations are very archaic. But the motivation behind that idea is something we should adapt.
For me it comes down to one basic rule: don't stay in a company for more than a few years. Learn as much as possible from your current company and give back as much back as you can. If you have the feeling that you stopped learning new stuff or get bored, switch. And even if you like your job, you should consider switching after a few years. Often you only realize that you were bored in your job after you switched to another one.
Another reason to switch is something I call "incest of ideas". It boils down to the problem that a team of people that only has minimal contact to others, tends to "invent" stuff that works around their current problem without seeing the larger issue in their architecture. The only way to prevent this is to get "fresh blood" into your team on a regular basis.
I know that freelancing is not for everyone. Me included. But do yourself a favour. Think about when you learned something new the last time or had a day without thinking that your coworkers suck. We are in a very unique situation. You as a developer can choose your company. There are companies lined up to hire developers. It would be stupid not to use this to your advantage. And yes, sometimes a new job is crappy. You got promised stuff and realized that they lied to you. But that's not a real problem. Switch again .
I started a new job three weeks ago and never learned as much as in those few weeks. Trust me. It will be worth it. You only have this one life. You should try to get the best out of it.