开发者

How can I print text to a webpage every second?

I want to m开发者_开发技巧ake a website write a message every second.

<?php echo '111';?>

How can do this?


If you want the user to see a message every second in their browser, this isn't doable in PHP. PHP is a server-side language, meaning that by the time the page reaches the browser, PHP's work is done.

You'll need a client-side language such as Javascript to accomplish this, using something like setTimeout: http://www.w3schools.com/jsref/met_win_settimeout.asp


Edit after OP's clarification:

If instead what you want is to execute the script once every X seconds, then you should look into cron. You can use cron to schedule your script to run as often as you desire.

So an example of how it might work is:

  1. You write a script that sends an email once
  2. You set your crontab to execute your script, say, once every hour
  3. Every hour, cron will execute your script, sending you an email


You cannot really do it with PHP. Instead, this would be accomplished with Javascript. If the message to be displayed must be supplied by the server, it complicates things significantly, requiring AJAX transactions. However, if the messages are predefined or can be calculated on the fly, it is fairly straightforward:

<div id='someId'>Message will go here</div>

<script type='text/javascript'>
  var textSpace = document.getElementById('someId').innerHTML;
  var refreshTimeout = setInterval(function() {
     // every second, add another ' message' into the element
     textSpace = textSpace + ' message';
  }, 1000);
</script>


You can put it in a loop like follows

    while(1)
    {
    echo 111;
    sleep(1);
    }


PHP is not well suited for what you want to do. Instead, use Javascript and the function setInterval(functionName, 1000), where functionName is a Javascript function that writes the message that you want.


Another way would be to refresh the page automatically:

<meta http-equiv="refresh" content="1">
<?php echo '111';?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜