每5秒运行一次功能的问题

时间:2015-09-25 08:21:08

标签: javascript php jquery mysql

我正在尝试创建一个通知系统,无论何时在数据库中创建新条目,用户都会看到通知。脚本自行循环遍历mysql表,直到检测到新条目,然后停止循环并显示通知。

我的目的是修改脚本,以便在通知之后,应该在检测到新记录时每隔五秒调用一次函数(check())。

我的问题是当我将脚本置于基于时间的循环(5秒间隔)时,即使插入新记录,循环也似乎无限期地运行。

 <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

<?php

$echo_time = time();
$interval = 5;
while(true){
 if ($echo_time + $interval >= time()){
  check();
  echo "$interval seconds have passed...";
  $echo_time = time(); // set up timestamp for next interval
}
// other uninterrupted code goes here.


function check()
{
 $timeStart = time();
 $today = date("Y-m-d H:i:s");       
 // Create connection
 $con = mysqli_connect('localhost','root','root','test');

 // Check connection
 if (mysqli_connect_errno($con))
 die ('Failed to connect to MySQL: ' . mysqli_connect_error() );

 // select where item is new

 if(isset($_POST['timestamp'])){
    $timestamp = $_POST['timestamp'];
 }else
 {
  // get current database time
  $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
  $timestamp = $row['now'];
 }
 $sql = "SELECT * FROM records WHERE insertDate > '$timestamp'";

 $newData = false;
 $notifications = array();

 // loop while there is no new data and is running for less than 20 seconds
 while(!$newData && (time()-$timeStart)<20){

  // check for new data
  $result = mysqli_query($con,$sql);
  while($row = mysqli_fetch_assoc($result)){
     $notifications[] = $row;
     $newData = true;
     echo "<script>
        $(document).ready(function() {
        $.sticky('The page has loaded!');
         var callnotification = function(){
         $.sticky('<b>A new Invoice has arrived!</b>');
         }
        callnotification;
       });
      </script>";
    }

   }

 // get current database time
 $row = mysqli_fetch_assoc(mysqli_query($con,'SELECT now() as now'));
 $timestamp = $row['now'];
 mysqli_close($con);

 }

1 个答案:

答案 0 :(得分:0)

您可以使用“setTimeout”函数

来实现此目的

表示例如:

var checkForNotification = function(){
   // ajax call to a function which check for a new notification
};

setTimeout(checkForNotification, 5000);