我创建了一个消息系统,当用户单击该链接时,该系统会在jquery对话框中打开。它会检查新消息的时间是5秒。问题是,在用户关闭对话框后,如果用户不刷新页面,它会继续检查消耗大量资源的消息。关闭对话框后有没有办法杀死函数?
打开对话框的代码。
$('body a#link').each(function() {
var $dialog = $('<div></div>');
var $link = $(this).one('click', function() {
$dialog
.load($link.attr('href'))
.dialog({
title: $link.attr('title'),
width: 500,
height: 300
});
$link.click(function() {
$dialog.dialog('open');
return false;
});
return false;
});
});
Messenger.php(加载到对话框中)
<script type="text/javascript">
$(function() {
$("form").submit(function() { return false; });
});
$('#message').keypress(function(e) {
if(e.which == 13) {
$.ajax({
type: "POST",
url: "includes/sendmessage.php",
data: $("#messageform").serialize(),
success: function(){
$("#message").val("");
}
});
}
});
setInterval(function() {
var msngr = $.ajax({
type: "GET",
url: "includes/checkmessages.php",
success: function(msg){
$('div#messages').html(msg);
$("div#messages").scrollTop($("div#messages")[0].scrollHeight);
}
});
}, 5000);
</script>
<div id="messages" style="width: 450px; height: 350px; overflow: auto;"><?php
include("includes/dbcon.php");
$result = mysql_query("SELECT * FROM messages WHERE message!='' ORDER BY id LIMIT 50") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
$username = $row['username'];
$message = $row['message'];
echo stripslashes($username) . ": " . stripslashes($message) . "<br />"; }
mysql_close($con); ?></div>
<form id="messageform" method="post" action="">
<input type="text" id="message" width="450px" maxlength="500" name="message" />
</form>
答案 0 :(得分:3)
您需要为重复代码指定一个变量
var refreshTimer=null;
refreshTimer = setInterval(function() {
var msngr = $.ajax({
type: "GET",
url: "includes/checkmessages.php",
success: function(msg){
$('div#messages').html(msg);
$("div#messages").scrollTop($("div#messages")[0].scrollHeight);
}
});
}, 5000);
然后,当对话框关闭时,您将要使用clearInterval()
来停止重新执行计时器。
if (refreshTimer) clearInterval(refreshTimer);
<强>更新强>
如果你想重新启用计时器,我会把整个事情扔进一个函数中。这样,您可以随时拨打stopMessageRefreshTimer();
或startMessageRefreshTimer();
。
var refreshTimer=null;
function stopMessageRefreshTimer(){
if (refreshTimer) clearInterval(refreshTimer);
}
function startMessageRefreshTimer(){
refreshTimer = setInterval(function() {
var msngr = $.ajax({
type: "GET",
url: "includes/checkmessages.php",
success: function(msg){
$('div#messages').html(msg);
$("div#messages").scrollTop($("div#messages")[0].scrollHeight);
}
});
}, 5000);
}
答案 1 :(得分:0)
您需要停止setInterval。这可以这样做:
var intervalId = setInterval(function(){},5000);
clearInterval(intervalId);
答案 2 :(得分:0)
使用window.clearInterval来停止对话框关闭事件的计时器
var timer = setInterval(function() {
var msngr = $.ajax({
type: "GET",
url: "includes/checkmessages.php",
success: function(msg){
$('div#messages').html(msg);
$("div#messages").scrollTop($("div#messages")[0].scrollHeight);
}
});
}, 5000);
$dialog.dialog({
close: function(event, ui) {
clearInterval(timer)
}
});