Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: A delay effect...

by Juerd (Abbot)
on Dec 30, 2001 at 19:49 UTC ( [id://135249] : note . print w/replies, xml ) Need Help??


in reply to A delay effect...

I want to be able print something after a pause of two seconds. I have not been able to do that with 'sleep'.
That's weird, because that's what sleep is for.
sleep 2 tells perl to wait for two seconds.

select's 4-argument form provides for another way of sleeping. This can also handle floating point number of seconds like 2.5 (you could also use Time::HiRes for that).

2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

Replies are listed 'Best First'.
Re: Re: A delay effect...
by kiat (Vicar) on Dec 30, 2001 at 19:58 UTC
    Hi Juerd,

    Yes, there is indeed a pause of two seconds. But say I have two print statements and I want the pause to come between them, is that possible?

    print "Congrats!<br>"; sleep 2; print "You guessed you it!";
    kiat
      UPDATE: This is my 100th post! :))

      Yes, but think about buffering. Perl won't flush it's buffer until it sees a newline.
      You have no \n after the <br>, so this is what happens:
      1. perl fills the buffer
      2. perl sleeps for two seconds
      3. perl appends to the buffer, and then flushes it because the end of the script is reached.
      Which of course is not what you want.

      You could put a \n after the <br>, or turn on the autoflush using $| = 1 (often seen obfuscated as $|++).

      print "First<br>\n"; sleep 2 print "Second\n"; ### $| = 1; print "First<br>"; sleep 2; print "Second";


      I recommend the newline solution, because HTML doesn't care about the newline being there, and autoflushing decreases performance.

      Information about $| and many other special variables can be found in perlvar.

      2;0 juerd@ouranos:~$ perl -e'undef christmas' Segmentation fault 2;139 juerd@ouranos:~$

        Hi juerd,

        Your solution doesn't seem to produce the desired result. There four statements are printed at the same time after the long pause, not one after another after each pause.

        kiat
      You could use NPH (non-parsed headers), which lets you send multiple pages on one request. Check this silly page for an example (delays 10 seconds).

      There were some tricks. The main one was I had to do use CGI qw(-oldstyle_urls) to make it work with Netscape 4.x. Basically, here is the way to do it:

      use CGI qw(-oldstyle_urls); my $q = new CGI; # ... if ($q->param('last')) { last_page($q); } else { next_page($q); } sub next_page { # ... $url = $q->url('-query' => 1); $last = ($url =~ /\?/) ? '&last=1' : '?last=1'; # Here is the delay, 10 seconds print $q->header('-Refresh' => "10;URL=$url$last"), # print the rest of the 1st page here... } sub last_page { # ... print $q->header(), # etc... }