Javascript 触发计时器的angularJS性能问题
我正在构建一个相当大的角度应用程序,我的问题是内存泄漏导致页面冻结。 单击一个按钮,我的应用程序打开一个弹出窗口,(在自定义指令的帮助下),该弹出窗口的内容被动态附加,并使用本地文件中的$http调用该弹出窗口。它工作正常 我使用chrome开发者工具,根据时间线给我的信息,提出了以下建议: 如您所见,在渲染发生之前,计时器会启动很长一段时间。当用户多次这样做(关闭弹出窗口并再次打开)时,这种情况发生的时间越来越多。除非他转到其他页面并返回或刷新页面。所以。。。。我怎样才能销毁所有以前的计时器,或者必须做些什么来收集垃圾,或者是必须做些别的事情。Javascript 触发计时器的angularJS性能问题,javascript,angularjs,settimeout,developer-tools,angular-directive,Javascript,Angularjs,Settimeout,Developer Tools,Angular Directive,我正在构建一个相当大的角度应用程序,我的问题是内存泄漏导致页面冻结。 单击一个按钮,我的应用程序打开一个弹出窗口,(在自定义指令的帮助下),该弹出窗口的内容被动态附加,并使用本地文件中的$http调用该弹出窗口。它工作正常 我使用chrome开发者工具,根据时间线给我的信息,提出了以下建议: 如您所见,在渲染发生之前,计时器会启动很长一段时间。当用户多次这样做(关闭弹出窗口并再次打开)时,这种情况发生的时间越来越多。除非他转到其他页面并返回或刷新页面。所以。。。。我怎样才能销毁所有以前的计时器,
您应该将按钮调用的函数包装为去盎司函数。请参阅下面的函数。这将确保每当用户单击按钮时,最后一个操作将被取消 在性能方面,请确保当用户关闭弹出内容时,它会从dom中删除 来源:
我建议使用$timeout而不是setTimeout memoryleak的一个可能解决方案是在Angular从DOM中删除元素时取消计时器,如本例所示:
var timer = $timeout(
function() {
console.log( "Timeout executed", Date.now() );
},
2000
);
// Let's bind to the resolve/reject handlers of
// the timer promise so that we can make sure our
// cancel approach is actually working.
timer.then(
function() {
console.log( "Timer resolved!", Date.now() );
},
function() {
console.log( "Timer rejected!", Date.now() );
}
);
// When the DOM element is removed from the page,
// AngularJS will trigger the $destroy event on
// the scope. This gives us a chance to cancel any
// pending timer that we may have.
$scope.$on(
"$destroy",
function( event ) {
$timeout.cancel( timer );
}
来自
var timer = $timeout(
function() {
console.log( "Timeout executed", Date.now() );
},
2000
);
// Let's bind to the resolve/reject handlers of
// the timer promise so that we can make sure our
// cancel approach is actually working.
timer.then(
function() {
console.log( "Timer resolved!", Date.now() );
},
function() {
console.log( "Timer rejected!", Date.now() );
}
);
// When the DOM element is removed from the page,
// AngularJS will trigger the $destroy event on
// the scope. This gives us a chance to cancel any
// pending timer that we may have.
$scope.$on(
"$destroy",
function( event ) {
$timeout.cancel( timer );
}