setinterval在ajax加载后继续运行

setinterval keeps running after ajax load

本文关键字:继续 运行 加载 ajax setinterval      更新时间:2023-09-26

我从页面(mypage.php)将内容加载到div(#mydiv)中。我从中获取内容的页面内部有javascript。

在mypage.php 中

 function refresh_feeds() {
//bla bla
}
$(function(){
    feed_timer = setInterval(refresh_feeds, 50000);
});

当我清理#mydiv的内容并从另一个页面(mypage2.php)加载内容时,在mypage.php中启动的setInterval将继续运行。

我的问题是,当mypage.php中的内容卸载时,我如何才能停止它

如何处理mypage.php的卸载事件?

var feed_timer;
function refresh_feeds() {
    //bla bla
}
$(function(){
    clearInterval(feed_timer);
    feed_timer = setInterval(refresh_feeds, 50000);
});
function refresh_feeds() {
  console.log(1);
}
$(function() {
  window.feed_timer = window.setInterval(refresh_feeds, 100);
});
$(window).bind("beforeunload",function() {
  window.clearInterval(window.feed_timer);
  window.feed_timer = null;
  return 1;
});

请在控制台中检查此

您必须清除Interval

clearInterval(feed_timer);

请确保将feed_timer保存在全局范围中