让函数每5秒运行一次
Problems getting function to run every 5 seconds
我正在尝试创建一个通知系统,每当在数据库中创建新条目时,用户就会看到通知。对于它自己,脚本循环遍历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);
}
可以使用"setTimeout"函数来实现
for example:
var checkForNotification = function(){
// ajax call to a function which check for a new notification
};
setTimeout(checkForNotification, 5000);
相关文章:
- 使用每500ms运行一次的jquery函数是个好主意吗
- For循环在Jquery中只运行一次
- 谷歌图表在运行应用程序时只能显示一次
- 使函数只运行一次(Javascript)
- 更改路由后,运行一次js脚本
- 只运行一次提取的脚本
- 可能只在for循环内部运行一次代码块
- 在单击事件中,第一次单击时激发代码一次,其余代码在所有单击时运行
- 在Flask中使用.getJSON请求时,只运行一次命令
- 运行“;非“;单击另一个函数中的函数仅一次
- JavaScript只有在最后一次被调用时才运行函数
- 数据互绑定问题:转换器只运行一次,无法绑定元素的 ID
- 您可以在节点.js上一次运行多个应用程序吗?
- 如何一次运行一次循环javascript
- 从命令行一次运行大量摩卡测试的好方法是什么
- 如何让 JavaScript 一次运行一个字符串
- 无法在一次运行中删除多个数组元素
- 如何使jquery函数一次运行一个
- 在一次运行中分配并返回一个变量
- 一次运行2个动画