I am new to programming and this is not clear to me:

for ($i = 0; $i < 10; $i++) { echo $i; sleep(2); } 

According to my idea, on the screen first would appear 0, then after two seconds 1 and every two seconds a new number and so on to 10. But they did not appear, 20 seconds passed and only after that all the numbers appeared simultaneously. I would like you to explain why this behavior of the sleep () function and the delay functions in general (in jquery delay (), sort of). I heard that this is somehow related to streams, buffers and other things, but please understand the newcomer in plain language about what these buffers are, what these streams are and how they are related to delay functions in programming. Thank you very much.

  • you need to flush the buffer at each iteration so that for ($i = 0; $i < 10; $i++) { echo $i; flush(); sleep(2); } for ($i = 0; $i < 10; $i++) { echo $i; flush(); sleep(2); } for ($i = 0; $i < 10; $i++) { echo $i; flush(); sleep(2); } and this is why it hangs with this performance ..... - Alexey Shimansky
  • If you run this script in the console, then it will output in turn. From this we can conclude that this question has nothing to do with cycles. - Ipatiev
  • @ AlekseyShimansky freezes due to the fact that the "buffer out of the box" is set, which does not require writing ob_start . Suppose my buffer value out of the box is 4096 . If you set the value off then the flush will work like in the console! By the way, I will answer immediately to a parallel question about the console. Yes, you have a buffer, but in the console it automatically loses its power to the value off - MaximPro

1 answer 1

First, there is not enough dumping of the output stream using flush and / or ob_flush .

Secondly, the browser is probably also smart and it’s too lazy to draw 2 characters each, so it’s waiting for some internal buffer to be filled. Try after each output to connect a script that will perform the delay.
I was wrong. The browser correctly processes html chunks:

 require('http').createServer(function (request, response) { response.writeHead(200, { 'Content-Type': 'text/html; charset=UTF-8' }); response.write('<!doctype html><title>Number in 2 seconds</title>'); ~(function go(i) { response.write('<p>' + i); response.flush(); if (i < 11) { setTimeout(go, 2000, i + 1); } else { response.end(); } })(0); }).listen(8082);