I have a Angular2 component that has a custom 3rd party JQuery plugin (which we must use and can't change) initialized within it in the OnInit event.However this 3rd party library makes liberal use of setIntervals. If I navigate away from the view the intervals are still active and on other views they keep triggering the widget behaviour.
The 3rd party component has no way to destroy it or clear intervals (which isn't great). I had hoped to just call destroy() or similar in Angular2 OnDestroy method.
I thought I should be able to use Zone to clean up. I did the following:
constructor(elementRef: ElementRef, public zone: NgZone) {
}
ngOnInit() {
this.zone.runOutsideAngular(() => {
$(this.elementRef).3rdPartyWidgetStart();
});}
ngOnDestroy() {
var componentzone=this.zone;
//So do something here to clear intervals set within Zone???
}
I thought that it would clear the intervals when I navigate away. However that doesn't seem to be the case. I also tried run
instead of runOutsideAngular
and it didn't seem to help. I then thought that Zone should know all of the intervals that have been set and I can clear them through that. It does appear to know them however doesn't seem possible to get access to the list and clear? Any ideas using Angular 2 RC - alternatively if I am just doing something totally wrong with Zones let me know. This is all new to me
I should say, that you are doing it on your own risk. Use Zone directly:
Zone.current.fork({
name: 'jquery', onScheduleTask: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
task: Task)=>
{
if(task.source === 'setInterval'){
console.log('capture', task);
//data has handleId property, interval id
this.interval = task.data;
}
return parentZoneDelegate.scheduleTask(targetZone, task);
}
}).run(()=>
{
setInterval(()=>
{
console.log('jquery interval', Zone.current);
}, 5000);
});
Somewhere in the code:
clearInterval(this.interval.handleId);
This code most probably lacks some checks, read documentation. Also i am not sure if angular is ok with that.