I've been trying to figure out how to stop a running setInterval, but despite making changes based on various resources, I still can't seem to get it to stop.
Currently, I have implemented a Mutation Observer that detects a class change. Once this change occurs and two specific conditions are met (related to the presence of other classes), cursor tracking is triggered successfully.
My goal is to halt the setInterval when one of the required classes, '.run-preview', is removed. I have included an 'else if' statement for this purpose, where I attempt to clearInterval as desired. Upon testing, the 'else if' condition appears to be functioning correctly.
To achieve this functionality, I have defined a global variable 'intervalCursor = setInterval(move,1000/60);'. Subsequently, I use this variable in conjunction with 'clearInterval(intervalCursor);' to terminate the interval when necessary.
const runPreview = document.querySelector('.projects');
new MutationObserver((mutations) => {
if (mutations[0].attributeName === 'class') {
console.log('Project list class changed');
if ($('html').hasClass('no-touchevents') && ($('.projects').hasClass('run-preview'))) {
var mouseX=window.innerWidth/2,
mouseY=window.innerHeight/2;
var intervalCursor = setInterval(move,1000/60);
var projectPreview = {
el:$('.image-container'),
x:window.innerWidth/2,
y:window.innerHeight/2,
w:300,
h:300,
update:function() {
l = this.x-this.w/2;
t = this.y-this.h/2;
this.el.css({
'transform':
'translate3d('+l+'px,'+t+'px, 0)' });
//console.log("transform");
}
}
$(window).mousemove (function(e){
mouseX = e.clientX;
mouseY = e.clientY;
//console.log("mousemove");
})
function move(){
projectPreview.x = lerp (projectPreview.x, mouseX, 0.1);
projectPreview.y = lerp (projectPreview.y, mouseY, 0.1);
projectPreview.update()
console.log("move");
}
function lerp (start, end, amt){
return (1-amt)*start+amt*end
}
} else if (!$('.projects').hasClass('run-preview')) {
clearInterval(intervalCursor);
return;
//$('#content-container').addClass('test');
}
}
})
.observe(runPreview, { attributes: true });
Is there something missing or incorrect in my setup?