I'm making a quick script to reveal my girlfriend's present, which I can't deliver in person. I want to add a pause in between clicks, so she can't accidentally go through all cases in a second.
var gifty = document.getElementById("gift");
var counter = 4;
var handler = function() {
gifty.style.backgroundPosition = counter * 722 + "px " + "0px";
counter -= 1;
switch (counter) {
case 3:
document.getElementById("head2").innerHTML = "Click it again! Click it again!";
break;
case 2:
document.getElementById("head2").innerHTML = "Hmmm, what could it be?";
break;
case 1:
document.getElementById("head2").innerHTML = "Any ideas what it could be?";
break;
case 0:
document.getElementById("head2").innerHTML = "Surprise! Your new sewing mahcine is waiting for you in Doha! Hope you like it. xxxxx";
gifty.removeEventListener("click", handler);
break;
}
}
gifty.addEventListener("click", handler);
You can use a setTimeout
to toggle the click handler:
const PAUSE_DURATION = 2000 // 2 seconds
const gifty = document.getElementById('gift')
const header = document.getElementById('head2')
const setText = text => header.innerHTML = text
let counter = 4
const handler = () => {
counter -= 1
switch (counter) {
case 3: setText('Click it again! Click it again! 😄 '); break
case 2: setText('Hmmm, what could it be? 🤔 '); break
case 1: setText('Any ideas what it could be? 😉 '); break
case 0: setText('Surprise! Your new sewing machine is waiting for you in Doha! Hope you like it. 😘 '); break
}
removeClickHandler()
setTimeout(() => addClickHandler(), PAUSE_DURATION)
}
const addClickHandler = () => gifty.addEventListener('click', handler)
const removeClickHandler = () => gifty.removeEventListener('click', handler)
addClickHandler()
<div id="gift">
<h2 id="head2"> Click here! ❤️ </h2>
</div>