您需要保存结果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);
}
}