Q:

WiFi connection in loop function

What I am trying to do is while connected locally in the esp8266 and give it a ssid and password, save them in a global variable and use them to start a connection inside loop function with a flag so it happens only once and let the program run while I check when the connection is complete. Do you foresee any problems with this application?:
setup(){
    wifi.mode(WIFI_AP_STA);
    setup softAP
    server.on("/",handleroot)
    server.begin()
}
loop(){
    server.handleClient()
    if(credential_submited){
        Wifi.begin(credentials);
        flag_connection_started =true;
        credential_submited = false;
        flag_for_internet_server=true;
    }
    if(WiFi.status()==WL_CONNECTED && flag_for_internet_server==true){
        server.on("/",handleroot)
        server.begin()
        flag_for_internet_server=false;
    }

I know there is also WifiManager But I am trying to do it on my own. The thing is some wifi networks take a lot of time to connect. More precisely they connect but then the esp doesn't get an ip and disconnects.
Thank you for your time

A:

WiFi.begin() in ESP8266WiFi library doesn't wait until the connection completes, it returns immediately.
You can check if the connection to WiFi network is established using WiFi.status() as most of the examples show. And it is not mandatory to wait for the connection in setup().
BTW: You can use a separate sketch to set the SSID and password in esp8266 and then in all other sketches not use WiFi.begin(), only wait for the connection to WiFi network to finish.

