Using Macrodroid:
- From the drawer, select variable and create a global variable of type boolean. Set it to false and save.
- Create a macro. On the Triggers tab, on the Connectivity section, select Wifi Enable.
- On the Actions tab, on the Conditions/Loops section, select Repeat actions, then "While condition repeat". On the Condition, go to the Connectivity section, select Wifi State, then Wifi is connected to, finally select Any network.
- On the Actions tab, on the Macrodroid specific section, select "Wait Before Next Action", set a time (I set it at 1mn).
- On the Actions tab, on the Connectivity section, select Connectivity check. Enter a website that the macro will keep checking if there is an internet connection to it or not. Set the timeout. Click the + and add a variable.
- On the Actions tab, on the Conditions/Loops section, select "If clause", under Macrodroid specific, select Macrodroid variable and choose the variable created on the previous section. Set its value to False.
- On the Actions tab, on the Screen section, select "Screen On/Off", choose Screen Off.
- On the Constraints tab, under the Screen and Speaker section, select "Screen On/Off", choose Screen On.
- Give the macro a name and save it.
The macro will look like the image below. Click the up and down arrows on the Actions section, to be able to move the actions up or down.
Click the 3-dot on the top right and select Test Macro.
Explanation: When the macro starts, it checks if Wifi enabled and the device is connected to any network. It waits for a certain time before checking if there is a connection to the website enter in step 5. If after the set timeout in step 5 there is no connection, the screen will be switched off.
The delay in step 4 also serves as a fail-safe mechanism when you switch the screen on again to allow for example to disable the macro.
Note: To see the Conditions/Loops section under the Actions tab, the macro must be saved. Then when opened for an edit, the section will be visible.