Reputation: 11
function destroy() {
let checkOnMeCard = document.querySelector('.timerCard.hideMe');
checkOnMeCard.classList.remove('hideMe');
checkOnMeCard.classList.add('.showMe');
console.log('Hello World!');
}
const bombTimer = setTimeout(destroy, 5000);
console.log(bombTimer);
window.addEventListener('click', () => {
console.log('Goodbye Cruel World');
// How do i stop the timer??
clearTimeout(bombTimer); // stop timer
});
Hi, I'm very new to Javascript so please bear with me...
I'm trying to run a timer that kicks in when a lack of mouse movement is detected, a class is added after the timer and then removed when a mouse click is detected. but I can't seem to find anything online JS wise that detects no mouse movement.
So for now i've got something that shows after 5 seconds, which works from what i can see in the console. But i need to have the same element disapear on click after the timer has run, But I'm not sure where I would add this, which i think is what i need somewhere after the timer has ran:
checkOnMeCard.classList.remove('.showMe'); checkOnMeCard.classList.add('.hideMe');
(.showMe has opacity: 1; .hideMe has opacity: 0;)
I hope this makes sense. Might help to know What im trying to essentially make in the long run is like a "screen saver" type thing for a website like you would on a pc.
Upvotes: 0
Views: 51
Reputation: 43
hope this helps you in some way:
let timeoutHandle;
const secondsMouseShouldStandStill = 5;
//we want the mousmove event to be throttled, so our resetMovementTimer is only called once every second:
document.body.addEventListener('mousemove', throttle(resetMovementTimer, 1000));
//reusable throttle function (credit to https://programmingwithmosh.com/javascript/javascript-throttle-and-debounce-patterns/)
function throttle(callback, interval) {
let enableCall = true;
return function(...args) {
if (!enableCall) return;
enableCall = false;
callback.apply(this, args);
setTimeout(() => enableCall = true, interval);
}
}
//this function cancelles the timeout when mouse movement is detected
function resetMovementTimer() {
window.clearTimeout(timeoutHandle);
timeoutHandle = window.setTimeout(function () {
executedAfterMouseStandsStill();
}, secondsMouseShouldStandStill * 1000);
}
//this is called after the mouse stands still for some time
function executedAfterMouseStandsStill() {
//do your css manipulations here...
}
Best regards, Mike
Upvotes: 0