I've been trying to properly use setTimeOut
but haven't been able to figure it out.
Expected Output:
if you click any button, a banner will slide into view, after 8 seconds it will disappear.
click anywhere else on the page and the banner disappear.
click the same button before the 8 seconds timer ends and a new 8 should start.
Actual output:
if you click any button a banner will slide into view, after 8 seconds it will disappear.
click anywhere on the page so the banner disappear.
click the same button before the 8 seconds timer ends, instead of starting a new 8-seconds the banner will finish off the remaining seconds of the first click then disappear.
Here is what I've tried and also a codesandbox: [a link] https://codesandbox.io/s/n7zvwn11yj
const getGreetingBanner =(e)=>{
let query = document.querySelector(e)
query.style.right = '8px';
let timer = setTimeout(() => {
query.style.right = '-165px';
}, 8000);
clearTimeOut(timer)
}
document.addEventListener('click', (e) => {
let triggeredElement = e.target.className;
if (triggeredElement === 'container') {
document.querySelectorAll('.banishBanner').forEach(function(x) {
x.style.right = '-180px';
})
}
})
HTML:
<div class="container">
<button onclick="getGreetingBanner('.thankyou')" type="button" class="accept">Accept</button>
<button onclick="getGreetingBanner('.comeBackSoon')" type="button" class="cancel">Cancel</button>
<div class="banishBanner thankyou">Thank You!</div>
<div class="banishBanner comeBackSoon">Come back soon.</div>
</div>
You must clear timeout when you clicking again on same button.
var timeout;
const getGreetingBanner =(e)=>{
let query = document.querySelector(e)
query.style.right = '8px';
//clearing timeout
clearTimeout( timeout );
timeout = setTimeout(() => {
query.style.right = '-165px';
}, 8000);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.