我有多个以javascript代码作为响应的ajax请求,一旦加载了新代码,我需要停止执行previos javascript代码,我的意思是停止间隔、函数、超时......
我的代码:
$.get("/ucmd", params, function(data) {
var $data = document.createElement("div");
$data.innerHTML = data;
var em = $data.getElementsByTagName("*");
for(var i=0;i<em.length;i++)
{
if(em[i].tagName === "SCRIPT")
{
if($("#"+em[i].id)) document.body.removeChild($("#"+em[i].id));
var script = document.createElement("script");
script.id = em[i].id;
script.language="javascript";
script.type="text/javascript";
script.innerHTML = em[i].innerHTML;
document.body.appendChild(script);
}
}
});
是否可以在加载新代码时停止执行以前的代码?
PS:我想使用纯javascript代码。
我的解决方案:
window.$timeout = {};
window.$interval = {};
window.$setTimeout = window.setTimeout;
window.$setInterval = window.setInterval;
window.$clearTimeout = window.clearTimeout;
window.$clearInterval = window.clearInterval;
window.setTimeout = function(id, code, delay) {
if(typeof $timeout[id] !== "undefined") clearTimeout(id);
$timeout[id] = $setTimeout(code, delay);
};
window.clearTimeout = function(id) {
$clearInterval($timeout[id]);
delete $timeout[id];
};
window.setInterval = function(id, code, delay) {
if(typeof $interval[id] !== "undefined") clearInterval(id);
$interval[id] = $setInterval(code, delay);
};
window.clearTimeout = function(id) {
$clearInterval($interval[id]);
delete $interval[id];
};