Sam and I are reading in the living room. The window is open and the temperature in the room is starting to drop. It's getting cold in the room.
[a] I think about closing the window, but decide I should ask Sam if it's OK to close the window because maybe Sam wants the window open. I say, "I'm going to close the window. Is that OK with you, Sam?"
=> Use "going to" when you've thought about doing something but haven't yet done it. In other words, you've had time to consider whatever it is that you are going to do.
[b] Without thinking it over, I get up and close the window.
=> Use "will" when you are about to do something that you haven't thought over. In other words, "will" is about instinct. You just do it.
Another set example,
I'm going to be a doctor! <I've thought about it (a great deal)>
I will be a doctor. <I know this in my heart>