Implement wifi connecting timeout on ESP32?

So here is the well-known WiFi connection code:

  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, pass);
  }

  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
   }
  Serial.print("Connected...");

The problem is if it can't connect to the hotspot for some reason, it will end up in an infinite while loop. I was thinking on some solution with the millis() function, but then I found the WiFi.waitForConnectResult() fuction and I came up with this:

  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, pass);
  }

  if (WiFi.waitForConnectResult() == WL_CONNECTED) {
    Serial.println("connected");
  } 
    else {
    Serial.println("not connected");
  }

Is this a good solution, to avoid infinite loop? If the ESP can't connect, it still can do the other things which does not need WiFi.

esp32 wifi api Networking APIs - ESP32 - — ESP-IDF Programming Guide latest documentation

Sure. If you look at the code for waitForConnectionResult, it is basically trying to connect 100 times with 100 msec delay in between so you get a timeout of ~10 seconds

I see, however a did a small experiment, I intentionally gave a wrong ssid, so it could not connect anyway. But the "timeout" did not take 10 secs, only about 2-3, then my code printed "not connected". How is that possible?

Look at the code. You have the source code right there on your PC. If any attempt returns an error, it does not keep trying