Are you using an ESP8266? If so, you need to insert some delays. Or you could make use of the yield() function.