我在每5秒后调用ajax来更新我的数据,我需要在单击按钮时停止该调用。 我的ajax功能是:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).complete(function(){
setTimeout(function(){get_text();}, 5000);
}).responseText;
$('#editor_Content').html(text);
}
此功能在
处调用$(document).ready(function(){
new get_text();
}
我需要在单击按钮时停止此调用,并在再次单击相同按钮时再次启动此调用。有什么建议吗?
我的按钮点击代码是
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
}
}
答案 0 :(得分:3)
您需要保存setTimeout
的结果,并在调用clearTimeout
函数时使用它,如下所示:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).complete(function(){
window.getTextTimeoutId = setTimeout(function(){get_text();}, 5000);
}).responseText;
$('#editor_Content').html(text);
}
$(document).ready(function(){
get_text();
}
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
if(window.getTextTimeoutId){
window.clearTimeout(window.getTextTimeoutId)
window.getTextTimeoutId = null;
}
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
if(!window.getTextIntervalId) //edited for not to create another call. fixed!
window.getTextTimeoutId = setTimeout(get_text, 0);
}
}
但出于您的目的,我认为setInterval
和clearInterval
会更好。以下是您的新代码的样子:
function get_text(){
var text = $.ajax({
type: "POST",
url: "getIt.php",
async: false
}).responseText;
$('#editor_Content').html(text);
}
$(document).ready(function(){
window.getTextIntervalId = window.setInterval(get_text, 5000);
}
function editit(){
var myVar = document.getElementById("editor_Content").getAttribute("contenteditable");
if(myVar=='true'){
if(window.getTextIntervalId){
window.clearInterval(window.getTextIntervalId)
window.getTextIntervalId = null;
}
document.getElementById("editor_Content").setAttribute("contenteditable", "false");
document.getElementById("editbtn").setAttribute("value","Edit Text");
} else{
document.getElementById("editbtn").setAttribute("value","Done Editing");
document.getElementById("editor_Content").setAttribute("contenteditable", "true");
if(!window.getTextIntervalId) //edited for not to create another call. fixed!
window.getTextIntervalId = setInterval(get_text, 5000);
}
}