我正在尝试制作一个有这个目标的脚本:
我用这段代码实现了它,它可以工作,但是计时器永远不会停止,并且它每5秒就会一直执行。
你知道我怎么解决这个问题? 提前致谢
var refreshIntervalId, refreshIntervalId2;
$("input:text:visible:first").focus();
refreshIntervalId2 = (function() {
return {
update: function() {
var pedidoid, url;
clearInterval(refreshIntervalId);
pedidoid = $("#pedidoid").val();
url = Routing.generate("get_pedido", {
id: pedidoid
});
return $.getJSON(url, function(json) {
clearInterval(refreshIntervalId2);
if (json.entregado === 1) {
return location.reload(true);
}
});
}
};
})();
refreshIntervalId = (function() {
return {
update: function() {
var url;
url = Routing.generate("get_pedidos");
return $.getJSON(url, function(json) {
var imgsrc;
clearInterval(refreshIntervalId);
$(".hero-unit").children("h1").text("Pedido nuevo!");
$(".hero-unit").children("h2").text("");
imgsrc = "/images/uploads/" + json.pedido.material.foto;
$("#imagenpedidomaterial").attr("src", imgsrc);
$(".cajapuesto").css({
position: "absolute",
top: json.pedido.puesto.y + "px",
left: json.pedido.puesto.x + "px"
});
$(".cajapuesto").addClass(json.kolorea);
$("#divimagenmaterial").show("slow");
$("#divcodbar").show("slow");
$("#pedidoid").val(json.pedido.id);
return setInterval(refreshIntervalId2.update, 5000);
});
}
};
})();
$(document).ready(function() {
return setInterval(refreshIntervalId.update, 5000);
});
$(document.body).on("keypress", function(e) {
var $micodbar, url;
switch (e.which) {
case 13:
$("#divmaterialincorrecto").hide();
$micodbar = $("#checkcodbar").val();
url = Routing.generate("get_material", {
codbar: $micodbar
});
return $.ajax(url, {
type: "GET",
contentType: "application/json",
success: function(data) {
var datos;
if (data === "null") {
return $("#divmaterialincorrecto").show("slow");
} else {
datos = jQuery.parseJSON(data);
return $(".row").show("slow");
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("Errorea");
alert(xhr.status);
return alert(thrownError);
}
});
}
});
答案 0 :(得分:4)
这是因为refreshIntervalId
和refreshIntervalId2
不是对您的计时器的引用,而是对包含方法update
的对象的引用,我认为这些方法是名称空间目的。
clearInterval
需要一个计时器作为参数,这些可以从setInterval
调用的返回值中获取。
您必须满足此形式的代码才能引用您的计时器以便将来清算:
//myTimer is a reference to your timer created by setInterval.
var myTimer = setInterval(func,interval);
//to clear myTimer, pass it to clearInterval
clearInterval(myTimer);
这样的结构就足够了:
$(document).ready(function() {
var firstInterval
, secondInterval
;
//if you are not creating local scopes, I suggest ditching the IFFE
//and go for a literal object instead.
var refreshIntervalId = {
update : function(){
...
return $.getJSON(url, function(json) {
...
clearInterval(firstInterval);
...
});
...
}
};
//run refreshIntervalId.update every 5 seconds
//timer referenced by firstInterval
firstInterval = setInterval(refreshIntervalId.update, 5000);
});
除此之外,您的keypress
处理程序应位于$(document).ready()
中,以确保DOM元素在运行之前已加载。