I'm trying to show a label when a user clicks a button. I've tried to use setTimeout to achieve this, but when you click the button multiple times before the timeout ends, this don't work properly.
This is what I got:
const [cameraLabelVisible, setCameraLabelVisible] = useState(false);
let labelTimer;
function labelVisible() {
setCameraLabelVisible(true);
labelTimer = setTimeout(() => {
setCameraLabelVisible(false);
clearTimeout(labelTimer);
}, 1500);
}
};
My question is: Is it posible reset the timer to the initial value (in this case 1500) by clicking the same button before the timer ends?
I want to show the label if the button is clicked multiple times before the time runs out.
You could clear the existing timer first:
const [cameraLabelVisible, setCameraLabelVisible] = useState(false);
let labelTimer;
function labelVisible() {
setCameraLabelVisible(true);
// clear the timer if there's another timer running
if(labelTimer) clearTimeout(labelTimer);
labelTimer = setTimeout(() => {
setCameraLabelVisible(false);
}, 1500);
}
My question is: Is it possible reset the timer to the initial value
(in this case 1500) by clicking the same button before the timer ends?
Yes, this can be achieved by clearing the existing timeout and creating a new timeout. This can be achieved as below:
const [cameraLabelVisible, setCameraLabelVisible] = useState(false);
let labelTimer;
function labelVisible() {
if(labelTimer) {
clearTimeout(labelTimer);
}
setCameraLabelVisible(true);
labelTimer = setTimeout(() => {
setCameraLabelVisible(false);
clearTimeout(labelTimer);
}, 1500);
}
};
I want to show the label if the button is clicked multiple times
before the time runs out.
This sounds like a different issue than what you asked above. If I'm understanding you correctly, the below will allow you to click the button multiple times within 1.5 seconds, and the label appear for only that amount of time before clearing.
const [cameraLabelVisible, setCameraLabelVisible] = useState(false);
let labelTimer = undefined;
function labelVisible() {
setCameraLabelVisible(true);
if(!labelTimer) {
labelTimer = setTimeout(() => {
setCameraLabelVisible(false);
labelTimer = undefined;
}, 1500);
}
};
Related
I am trying to add a feature to my game where an img appears after a set amount of time. The is only displayed for a set time before it disappears again or until it is clicked.
Here is my code below but it doesn't work because the clearInterval is ending the disappear function before it executes. But without it, the timer continues and the image appears and disappears at the same time.
How would I make it so the image stays for 5 seconds, then disappears again, then next time the image appears it stays for 5 seconds again?
const bunnyRocket = document.getElementById('bunny-rocket');
bunnyRocket.hidden = true;
bunnyRocket.addEventListener('click', () => {
console.log('You got it');
player.carrots += 1000;
bunnyRocket.hidden = true;
})
const rocketAppear = setInterval(bunnyRocketAppear, 5000);
function bunnyRocketAppear() {
let disappear = setInterval(() => {
console.log('DISAPPEAR');
bunnyRocket.hidden = true;
}, 5000)
console.log('SHOULD APPEAR NOW');
bunnyRocket.hidden = false;
clearInterval(disappear);
}
Your bunny appears every 5 seconds but also disappears after 5 seconds. You might want to make your bunny disappear before he appears again (e.g make him disappear after 3s).
Additionally, since the bunny only disappears once for every time he appears, you'd want your second interval to be a timer instead
const bunnyRocket = document.getElementById('bunny-rocket');
bunnyRocket.hidden = true;
bunnyRocket.addEventListener('click', () => {
console.log('You got it');
player.carrots += 1000;
bunnyRocket.hidden = true;
})
const rocketAppear = setInterval(bunnyRocketAppear, 5000);
function bunnyRocketAppear() {
//everytime he appears, set a timeout to make him disappear after 3s
let disappear = setTimeout(() => {
console.log('DISAPPEAR');
bunnyRocket.hidden = true;
}, 3000)
console.log('SHOULD APPEAR NOW');
bunnyRocket.hidden = false;
//If we do clearTimeout(disappear), the bunny won't disappear :(
}
I am building a React App and I have implemented a slider in my app. By default my slider is automatically but I made a toggle button so the user can stop the automatization at any tine.
Of course I ușe setInterval to make this auto-sliding effect. When I press the toggle first time it stops, but when I start it again and try to stop it another time it doesn't work and the auto-sliding continues when it should stop.
This is my code:
const toggle = document.querySelector(".toggle-container");
const toggleDot = document.querySelector(".toggle");
let autoSliding = true;
let slidingInterval = setInterval(() => {
nextButton.click();
}, 2500);
const stopAutoSliding = () => {
toggleDot.style.left = "10%";
toggle.style.background = "#ccc";
autoSliding = false;
clearInterval(slidingInterval);
}
const restartAutoSliding = () => {
toggleDot.style.left = "calc(90% - 20px)";
toggle.style.background = "#0c46b3";
autoSliding = true;
let slidingInterval = setInterval(() => {
nextButton.click()
}, 2500);
}
toggle.addEventListener("click", () => {
if (autoSliding) {
stopAutoSliding();
} else {
restartAutoSliding();
}
});
nextButton is just a button for which I set an addEventListener method for click events and it just simply makes the slider to move to the next slide.
If you wanna see it working follow this link.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to customize single click event to double click. And it have to work if second click is clicked in 300 ms.
Something like this should work. Basically you can save the first click, and set a timer to reset that click if no other click is there.
I'm sure there are plenty of better ways to do this, but this works:
let clicked = false;
const timeout = 300;
let timer;
function onClickHandler(e) {
console.log('click');
document.querySelector('#result').innerText = '';
if (timer) window.clearTimeout(timer);
if (!clicked) {
console.log('first time');
clicked = true;
timer = window.setTimeout(() => clicked = false, timeout);
} else {
console.log('double click');
clicked = false;
document.querySelector('#result').innerText = 'Double click!';
}
}
#result{background:red;}
<div onclick="onClickHandler(event)">Click me twice</div>
<div id="result"></div>
Description
Here is an example using the Timeout built into JavaScript
Example:
// the double click time amount
const doubleClickTimeout = 300
// timer variable used to store our timeout pointer
let timer = undefined
// clear function that kills the timeout/timer and variable
let clear = () => {
if (timer) clearTimeout(timer)
timer = undefined
}
// starts the timeout/timer
let clickStart = () => {
timer = setTimeout(clear, doubleClickTimeout)
}
// gets the area you want to monitor
const doubleClick = document.getElementById("doubleClick")
// set up a onclick event on the doubleClick variable that points to the doubleClick div
doubleClick.onclick = () => {
// if timer isn't undefined then we have a double click
if (timer) {
console.log("double click detected")
// call the clear function: clear the timer
clear()
} else {
// call the clickStart function: start a timer
clickStart()
}
}
<div id="doubleClick">this is a clickable area with custom double clicking</div>
I am have some issues resetting my timer when no longer idle. I am using Vue Idle for this, which is a wrapper for idle.js.
So I have a modal with the id timeout-modal. When Vue Idle triggers the idle function, I call showWarningMessage.
Within this function, I first display my modal. I then create a timer which my modal uses to do a countdown. So this all works fine.
<script>
export default {
data() {
return {
timerId: 0,
remainingTimeoutSeconds: 10000
}
},
computed: {
second() {
return this.remainingTimeoutSeconds / 1000;
}
},
onIdle () {
this.showWarningMessage();
},
methods: {
showWarningMessage() {
this.$bvModal.show('timeout-modal');
this.warning = true;
this.timerId = setInterval(() => {
this.remainingTimeoutSeconds -= 1000;
}, 1000);
},
}
}
</script>
Now within the modal there is a continue button. When pressed, it should basically reset the above timer. At the moment I have
handleContinueButtonClick(response) {
if (response.data.success) {
console.log("IN")
this.$bvModal.hide('app-timeout-reminder-modal');
clearInterval(this.timerId);
return;
}
}
So what this should do is hide the modal, and then reset the timer back to 10 seconds. It is entering the above as the console is printing IN. The modal is also
hidden when I click OK.
However, the next time the modal is displayed, the timer is already near 0 as it did not reset back to 10.
Is there any reason why I cant get this back to 10 seconds? I thought clearInterval should reset the timer?
Thanks
I thought clearInterval should reset the timer?
Do you mean this.remainingTimeoutSeconds is set automatically when calling clearInterval?
The answer is no.
You need to reset that value as 10000 like blow;
handleContinueButtonClick(response) {
if (response.data.success) {
console.log("IN")
this.$bvModal.hide('app-timeout-reminder-modal');
this.remainingTimeoutSeconds = 10000;
clearInterval(this.timerId);
return;
}
}
or
showWarningMessage() {
this.$bvModal.show('timeout-modal');
this.warning = true;
this.remainingTimeoutSeconds = 10000;
this.timerId = setInterval(() => {
this.remainingTimeoutSeconds -= 1000;
}, 1000);
}
I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn't moved for more than 1 minute, then we have to alert the user.
How its possible, are there any special events for this? (Only for IE in javascript)
Set a timeout when the mouse is moved one minute into the future, and if the mouse is moved, clear the timeout:
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 60000);
}
Here's a one-and-done function that can check any element for movement:
function mouse (element, delay, callback) {
// Counter Object
element.ms = {};
// Counter Value
element.ms.x = 0;
// Counter Function
element.ms.y = function () {
// Callback Trigger
if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
};
// Counter Callback
element.ms.callback = callback;
// Function Toggle
element.ms.toggle = function (state) {
// Stop Loop
if ([0, "off"][state]) clearInterval(element.ms.z);
// Create Loop
if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
};
// Function Disable
element.ms.remove = function () {
// Delete Counter Object
element.ms = null; return delete element.ms;
};
// Function Trigger
element.onmousemove = function () {
// Reset Counter Value
element.ms.x = -1;
};
// Return
return element.ms;
};
Usage:
mouse(element, delay, callback)
Examples:
Make a video player hide the mouse after 5 seconds when idle and fullscreen
let x = mouse(video, 5000, function (a) {
if (document.webkitIsFullScreen) video.style.cursor = "none";
});
x.toggle(1); addEventListener("mousemove", function () {
video.style.cursor = "auto";
});
Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):
let x = mouse(chatBox, (45e3), function (a) {
chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
});
x.toggle(1); x.addEventListener("mousemove", function () {
chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
});
Is there not a way to set a timer to start incrementing after every mouse movement event?
If it gets to a minute then pop up the message box, but every time the mouse moves the timer gets reset.
Use a timer that resets its value on mousemove event.
If timer reaches 1 minute --> Do something.
More info on timer here http://www.w3schools.com/js/js_timing.asp
And more info on catchin mouse events here http://www.quirksmode.org/js/events_mouse.html
Yes, you have a onmousemove event in Javascript, so to achieve what you need you just have to do code something like this:
startTimer();
element.onmousemove = stopTimer(); //this stops and resets the timer
You can use it on the document body tag for instance.
UPDATE: #Marius has achieved a better example than this one.
You can use the onmousemove event. Inside it, clearTimeout(), and setTimeout(your_warning, 1 minute).
You could use this script/snippet to detect the mouse pointer position and "remember" it. Then use a timer "setTimeout(...)" to check the position let's say every second and remember that time.
If more than one minute passed and the position hasn't changed, you could alert the user.