Normally, I’d set the interval to a variable and then clear it like var the_int = setInterval(); clearInterval(the_int); but for my code to work I put it in an anonymous function:
function intervalTrigger() {
setInterval(function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000);
};
intervalTrigger();
How do I clear this? I gave it a shot and tried var test = intervalTrigger(); clearInterval(test); to be sure, but that didn’t work.
Basically, I need this to stop triggering once my Google Map is clicked, e.g.
google.maps.event.addListener(map, "click", function() {
//stop timer
});
The setInterval method returns a handle that you can use to clear the interval. If you want the function to return it, you just return the result of the method call:
function intervalTrigger() {
return window.setInterval( function() {
if (timedCount >= markers.length) {
timedCount = 0;
}
google.maps.event.trigger(markers[timedCount], "click");
timedCount++;
}, 5000 );
};
var id = intervalTrigger();
Then to clear the interval:
window.clearInterval(id);
// Initiate set interval and assign it to intervalListener
var intervalListener = self.setInterval(function () {someProcess()}, 1000);
function someProcess() {
console.log('someProcess() has been called');
// If some condition is true clear the interval
if (stopIntervalIsTrue) {
window.clearInterval(intervalListener);
}
}
the_int=window.clearInterval(the_int);
Simplest way I could think of: add a class.
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause/unpause</button></p>
Related
My function is running twice , I tried using boolean value to stop it but it doesn't work, here is my code :
window.onload = function(){
setTimeout(addbutton, 2940) // Please increase it if it doesn't work, it doesn't work well if your connection is too long
};
function addbutton(){
var hreflink = "/admin/users/delete/"+id;
var Reportuser = document.getElementsByClassName("sg-button sg-button--solid-light sg-button--full-width");
var x = Reportuser.length-1
Reportuser[x].insertAdjacentHTML('beforebegin', '<button id=button class="sg-button sg-button--solid-mint sg-button--small sg-button"><span class="sg-button__text">Delete</span></button>');
console.log("%cButton added","color: blue; font-size: 20px");
function myFunction() {
window.location.href = hreflink;
}
document.getElementById("button").addEventListener("click", myFunction);
}
Refactored and converted your code to a minimal reproducable example using event delegation. The timeout works, once. If you are experiencing problems with connection times, maybe you should check async functions
setTimeout(addbutton, 500);
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.dataset.clickable) {
console.clear();
return console.log("Yes! It's clicked!");
}
return true;
}
function addbutton() {
[...document.querySelectorAll(".sg-button")].pop()
.insertAdjacentHTML("beforeend", `<button data-clickable="1">Delete</button>`);
console.log("button added to last div.sg-button ...");
}
.sg-button {
margin-bottom: 1.5rem;
border: 1px solid #999;
padding: 0.2rem;
width: 5rem;
text-align: center;
}
.sg-button button {
display: block;
margin: 0 auto;
}
<div class="sg-button sg-button--solid-light sg-button--full-width">1</div>
<div class="sg-button sg-button--solid-light sg-button--full-width">2</div>
I'm using a .slideToggle to show a div once an image is clicked. I want the div to disappear 10 seconds after the last time the toggle is clicked. The problem is that if I click the image a few times, the duration is 10 seconds after the first click and not the last. If you view the fiddle (I used a shorter duration for testing) and click the image a few times you will see what I mean.
Does anyone have any idea how I can get this working as desired? Any help would be greatly appreciated!
Fiddle: https://jsfiddle.net/7fy536nv/
Requirements...
The div should show for 10 seconds then disappear
The div will disappear if the image is clicked again
The div will disappear if something outside the div is clicked
HTML
<div class="box-new">
<a href="box-link" id="box-link">
<img src="https://dummyimage.com/100x60/ff0000/fff.png">
</a>
</div>
<div id="empty-box">jkhsahg akjfhsajk fhas jklsad flkasd hfjkashd fjka sdkjfh adskjfhs dakjfh kafh sdah dhjaf</div>
CSS
body, html {
margin: 0;
}
#empty-box {
display: none;
position: absolute;
background: #000;
top: 60px;
width: 240px;
padding: 20px;
left: 0;
color: #fff;
text-align: center;
font-family: "open sans", "arial";
font-size: 14px;
font-weight: 600;
line-height: 18px;
z-index: 1;
}
JS
$('#box-link').click(function(event){
event.stopPropagation();
$("#empty-box").slideToggle(400);
setTimeout(function() {
$("#empty-box").slideUp();
}, 5000);
return false;
});
$("#empty-box").on("click", function (event) {
event.stopPropagation();
});
$(document).on("click", function () {
$("#empty-box").slideUp(400);
});
Assign your call to setTimeout to a variable declared in the outer scope and clear it with clearTimeout in every subsequent event:
var timeout;
$('#box-link').click(function(event){
clearTimeout(timeout);
event.stopPropagation();
$("#empty-box").slideToggle(400);
timeout = setTimeout(function() {
$("#empty-box").slideUp();
}, 5000);
return false;
});
The setTimeout function returns a value that you can cancel using clearTimeout.
So in your code, store the return value, and each time it is clicked, cancel the previous timeout and restart a new one.
var timeout = null;
function test()
{
if( timeout !== null )
clearTimeout(timeout);
timeout = setTimeout(..., 10000);
}
It's quite simple, really. The key is placing your setTimeout in a variable and calling clearTimeout(variable).
Example:
let someVar = false,
someTime = 5000,
msgTimer = document.getElementById('timer'),
timer,
current,
displayTimer = false;
$('.yourButton').on('click', someFunc)
function someFunc() {
if (someVar) {
clearTimeout(someVar) // <<< juice is here
console.log('cleared timeout!')
}
timer = performance.now()
someVar = setTimeout(function () {
clearInterval(displayTimer)
console.log(someTime / 1000 +
' seconds passed since last click...')
someVar = false
displayTimer = false
msgTimer.innerHTML = ''
}, someTime)
/**
* ¯\_(ツ)_/¯
* ignore past this point, rest is timer
*
* ˙ʇᴉ pǝǝu ʇ,uop no⅄ ˙ʎllɐǝɹ
**/
if (displayTimer) {
clearInterval(displayTimer)
displayTimer = false
}
displayTimer = setInterval(function () {
current = performance.now()
msgTimer.innerHTML = Math.max(timer + 5000 - current,0)
.toFixed(2) + 'ms'
}, 15)
}
#timer {
font-family: monospace;
text-align:right;
display: inline-block;
width: 100px;
font-size: 1.2rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="yourButton">Don't click. Think.</button>
<span id="timer"></span>
Reduced interval to 5 seconds for faster testing.
Here is a solution to show a div for a maximum of 10 seconds...
And hide it if user clicks anywhere before this delay.
There is no problem with the delay if user clicks often or repeately...
Because I took care of resets.
I created a CodePen, with a timer displayed aside the cart link, to show the time passing.
And here is a CodePen with the exact same code as in the below snippet, if your want to play with it.
var emptyCart = $("#emptyCart");
var cartTimer;
var carMaxTime = 10000;
// Function to hide the cart
var hideCart = function(){
emptyCart.dequeue().slideUp("slow");
}
// Function to show the cart
var showCart = function(){
emptyCart.dequeue().slideDown("slow");
clearTimeout(cartTimer); // Just to be sure We have only one timer running
cartTimer = setTimeout(function(){
hideCart();
},carMaxTime);
}
// Function to handle click on the cart link
$("#clickCart").click(function(){
$(document).off("click",hideCart()); // Just to prevent a slideUp which would counter-act a slideUp
if(emptyCart.is(":hidden")){
showCart();
}
setTimeout(function(){ // 1ms delay to use this event handler on next click.
$(document).on("click",function(){
hideCart();
$(document).off("click",hideCart()); // Unbind this handler once used.
});
},1);
});
#emptyCart{
display:none;
width:100px;
background:#000;
color:#fff;
height:30px;
margin-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickCart">
Cart
</div>
<div id="emptyCart">
No items
</div>
How do I wait for an element to be displayed/seen by the user? I have the following function, but it only checks to see if the element exists and not whether it is visible to the user.
function waitForElementDisplay (selector, time) {
if (document.querySelector(selector) != null) {
return true;
} else if (timeLimit < timeSince) {
return false;
} else {
timeSince += time;
setTimeout(function () {
waitForElementDisplay(selector, time, timeLimit, timeSince);
}, time);
}
}
It's a bit confuse, are you trying a simple "sleep"?
You can wait element load using:
document.querySelector(selector).onload = function() {
// Your code ...
}
Some working snippet, run it:
// Triggering load of some element
document.querySelector("body").onload = function() {
// Setting the timeout and visible to another element
setTimeout(function () {
document.querySelector("#my_element").style.display = "block" /* VISIBLE */
}, 1000);
}
#my_element{
width: 100px;
height: 100px;
background-color: red;
display: none; /* INVISIBLE */
}
<div id="my_element"></div>
If you want to wait time as you have set to the function and the selector which should appear after this time.. You can mind about a simple setTimeout() and CSS.
Run the example below, hope it helps:
// Triggering, in my exemple i've used: WINDOW ONLOAD
window.onload = function() {
waitForElementDisplay("#my_element", 1000);
}
function waitForElementDisplay (selector, time) {
// Check the DOM Node in console
console.log(document.querySelector(selector));
// If it's a valid object
if (typeof document.querySelector(selector) !== "undifined") {
// Setting the timeout
setTimeout(function () {
document.querySelector(selector).style.display = "block" /* VISIBLE */
}, time);
}
}
#my_element{
width: 100px;
height: 100px;
background-color: red;
display: none; /* INVISIBLE */
}
<div id="my_element"></div>
You could use jQuery .ready()
selector.ready(function(){
// do stuff
})
I'm working with this js fiddle here: http://jsfiddle.net/tPx6x/
The animation works like so
You hover over the text, a circle fades in & begins to pulse 1 second later for as long as your mouse is over the text.
When your mouse pointer leaves the text, the pulse stops after one second and the circle fades out.
The issue arises when you do this:
Put your mouse over the text, remove the pointer from the text, THEN place the pointer back over the text before the script has a chance to finish(1-1.4s).
You won't be able to make the circle appear properly agin...you will have to allow the script to reset. That is the problem.
What is the best way to tackle this issue?
Example code:
<div class='circle__title_project-management'>
<h1>project management</h1>
</div>
<div class='circle__project-management hidden'></div>
.circle__project-management, .circle__title_project-management
{
display: inline-block;
cursor: pointer;
}
.circle__project-management
{
margin-left: 8px;
vertical-align: -4.07px;
background-color: transparent;
border: 2px solid #00DBFF;
width: 30px;
height: 30px;
border-radius: 90px;
top: 280px;
left: 40px;
}
.hidden
{
visibility: hidden;
}
.visible
{
visibility: visible;
}
.animate-infinite
{
animation-iteration-count: infinite;
-moz-animation-iteration-count: infinite;
-webkit-animation-iteration-count: infinite;
}
var circleTitle = $('.circle__title_project-management h1');
var circle = $('.circle__project-management');
var initTimeout = 1000;
var initTimeoutPlus = 1400;
circleTitle.mouseover( function() {
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
});
circleTitle.mouseleave( function() {
setTimeout( function() {
circle.stop().removeClass('pulse animate-infinite visibility');
circle.addClass('fadeOut');
}, initTimeout);
setTimeout( function() {
circle.removeClass('fadeOut');
circle.addClass('hidden');
}, 1400);
});
You should note that setTimeout has a return value. You want to clear previous timeouts before you start new ones; otherwise you can get a timeout queue which completely skews your animations. Something like this:
var myTimeout;
...
clearTimeout(myTimeout);
myTimeout = setTimeout(...);
Not sure if this is exactly what you were going for, but along these lines: http://jsfiddle.net/FYY38/
More info here: http://www.w3schools.com/js/js_timing.asp
Also, it looks like the circle.stop() call is doing nothing (as it's css-animated)
To avoid antagonist behaviours, maybe add a class to your element to tag it when the event is triggered and remove it when another is triggered.
That way you can stay in control of what's going on.
you can set time out to mouse over function to cover the time delay for mouseleave.
note that the first run must be without delay
var initTimeout = 1000;
var initTimeoutPlus = 1400;
var firstrun = true;
circleTitle.mouseover( function() {
if (firstrun) {
initTimeoutPlus = 0;
firstrun = false;
} else initTimeoutPlus = 1400;
setTimeout(function() {
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
}, initTimeoutPlus);
});
Probably if you just add a key on mouseover, and toggle it after mouseleave, and before you trigger any mouseleave timeout events, check the key, if it is set, ignore, else go ahead and execute mouseleave
this way if the key is "on" it means a mouse over occurred, if it was off, it means the mouseleave occurred and it is still occurring
var key = false;
circleTitle.mouseover( function() {
key = true;
circle.removeClass('hidden');
circle.addClass('animated fadeIn');
setTimeout( function() {
circle.addClass('pulse animate-infinite');
circle.removeClass('fadeIn');
}, initTimeout);
});
circleTitle.mouseleave( function() {
key = false;
setTimeout( function() {
if (!key){
circle.stop().removeClass('pulse animate-infinite visibility');
circle.addClass('fadeOut');
}
}, initTimeout);
setTimeout( function() {
if (!key){
circle.removeClass('fadeOut');
circle.addClass('hidden');
}
}, 1400);
});
im having a prob with javascript which has been bugging me for hours now. I need to delay a css popup so that if you just scroll mouse around page you wont get loads of popups.
Whatever i try it either makes the popup act goofy, poping up after x seconds with a swipe of any link, auto closing etc etc. if i add a timer to the mouseover it starts acting weird, if i then delete the timer for mouseout it works fine but you can no longer mouseover menu before it closes, also tried adding negative margin and it autocloses
cheers all
javscript
<script type="text/javascript">
var span = document.querySelectorAll('.pop');
for (var i = span.length; i--;) {
(function () {
var t;
span[i].onmouseover = function () {
hideAll();
clearTimeout(t);
this.className = 'popHover';
};
span[i].onmouseout = function () {
var self = this;
t = setTimeout(function () {
self.className = 'pop';
}, 300);
};
})();
}
function hideAll() {
for (var i = span.length; i--;) {
span[i].className = 'pop';
}
};
</script>
css
.pop {
position:relative;
}
.pop div {
display: none;
}
.popHover {
position:absolute;
}
.popHover div {
background-color:#FFFFFF;
border-color:#AAAAAA;
border-style:solid;
border-width:1px 2px 2px 1px;
color:#333333;
padding:5px;
position:absolute;
z-Index:9999;
width:150px;
display: inline-block;
margin-top: -20px;
}
Using jquery might be a little more helpful for what you are trying to do. Try something like this:
// Use a CDN to take advantage of caching
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var t;
$('.pop').on('mouseover', $.proxy(function () {
hideAll();
clearTimeout(t);
this.addClass('popHover');
this.removeClass('pop');
}, this));
$('.pop').on('mouseout', $.proxy(function () {
var self = this;
t = setTimeout(function () {
self.addClass('pop');
self.removeClass('popHover');
}, 300);
},this));
function hideAll() {
// Since you are calling this from the mouseover function of all the
// elements with the 'pop' class, I dont understand what the purpose of this class
// is so it might not be entirely correct.
$('.pop').addClass('pop');
}
</script>
Let me know if this helps. If you still need it. It would be helpful to have a fiddle to maybe tweak to give you a more accurate response.