Situation:
When the user click on a cell of "#test" table it will run "update_func" every 10 seconds.
When the user click on the same cell/ another cell, another "update_func" run again and there are multiple "update_func" running every 10 seconds.
Question:
I would like to stop the previous running "update_func" before a new one start, where should I use the clearTimeout() function to avoid multiple "update_func" keep running?
I have the following script:
$("#test").on("click", td, function() {
//do something..
update_func(v1,v2,v3);
});
function update_func(v1,v2,v3){
$.ajax({
url:"update.php",
method:"POST",
data:{testvalue:v1},
success:function(data){
$('#testbox').html(data);
}
}).always(function () {
window.setTimeout(function() { update_func(v1,v2,v3); }, 10000);
});
}
Save a reference to the timeout ID in the outer scope, assign the setTimeout call to it inside the always, and on click, clear the timeout:
let timeoutId;
$("#test").on("click", td, function() {
//do something..
clearTimeout(timeoutId);
update_func(v1,v2,v3);
});
function update_func(v1,v2,v3){
$.ajax({
url:"update.php",
method:"POST",
data:{testvalue:v1},
success:function(data){
$('#testbox').html(data);
}
}).always(function () {
timeoutId = window.setTimeout(function() { update_func(v1,v2,v3); }, 10000);
});
}
Related
I use a function to load a page with jQuery but only after a certain delay after hovering over a li. For that I use setTimeout on the mouseover and try to kill it on the mouseleave if the mouse hovered for less than 500ms over the li. However, the jQuery.ajax still launches, so basically, if I hover over all lis, that will launch plenty of xhr even if I stay only 1ms on the li.
var timer2;
var delay2 = 500;
$('body').on('mouseover','li',function(){
timer2 = setTimeout(function() {
var url="res.php";
jQuery.ajax(
{
type: 'POST',
url:url,
success: function(data){
$('#res').html(data);
}
});
}, delay2);
});
$('body').on('mouseleave', 'li', function() {
clearTimeout(timer2);
});
The problem here is simple. You use mouseover, mouseover can fire multiple setTimeouts while you are over the element.
$("div")
.on("mouseover", function(){ console.log("mouseover"); })
.on("mouseenter", function(){ console.log("mouseenter"); });
span { background-color: red;
font-size: 2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<span>Move mouse here</span> to <span>here</span> to <span>here</span></div>
So each time you move over elements inside of the parent, it fires another mouseover. So if that is the case you will create multiple events. So if you see multiple ajax calls for an li, that may be a reason why.
So change it to mouseenter, next cancel the event inside of enter OR track the events via the li itself and not a global.
$("ul")
.on("mouseenter", "li" function(){
$(this).data("timer", setTimeout( function () {});
}).on("mouseleave", "li" function(){
var id = $(this).data("timer");
if (id) window.clearTimeout(id);
})
And if you really want to be sure, clear the timeout on mouseenter....
Just clear your timeout before setting it again :
var timer2 = null;
$('body').on('mouseover','li',function(){
clearTimeout(timer2);
timer2 = setTimeout(function(){ .....
You need to initialize the timeout to null, otherwise you'll get an error can't clear timeout of undefined.
Also, try this to trigger the mouseleave :
$('body').on('mouseover','li',function(){
// ...
$(this).off("mouseleave").on("mouseleave", () => clearTimeout(timer2))
});
Edit : Working snippet
var timer2 = null;
var delay2 = 2000;
$('body').on('mouseover', 'li', function() {
clearTimeout(timer2);
console.log("Setting timeout...")
timer2 = setTimeout(() => console.log("Ajax call!"), delay2);
$(this).off("mouseleave").on('mouseleave', () => {
console.log("Clearing timeout.")
clearTimeout(timer2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li>Hover over me</li>
<li>Over me too</li>
Give an id to that specific li and use as below. This works. Check console Networks tab for verification.
var timer2;
var delay2 = 500;
var ajax;
$('body').on('mouseover','li#one',function(){
console.log("Mouse over");
clearTimeout(timer2);
timer2 = setTimeout(function() {
if(ajax) {ajax.abort();}
var url="res.php";
ajax = $.ajax(
{
type: 'POST',
url:url,
async:true,
success: function(data){
$('#res').html(data);
}
});
}, delay2);
});
$('body').on('mouseleave', 'li#one', function() {
console.log("Mouse left");
clearTimeout(timer2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="one">One</li>
<li>Two</li>
There are few ways to solve this problem
abort your request after mouseleave
use variable inside callback to tell it "don't do it"
abort your request
// ...
var request;
$('body').on('mouseover','li',function(){
// ... I omited `setTimeout` to simplify the explanation
// you have to make this variable to be able to control your requests
var xhr = new window.XMLHttpRequest();
// here we save our request
request = jQuery.ajax(
{
// ...
// note this change here, it is required for jquery 3.0 and more
xhr : function(){ return xor; }
});
// ...
});
$('body').on('mouseleave', 'li', function() {
// ...
// now we can `abort` it any time user mouse leaves
request.abort();
});
Question about abort on SO
use variable
// ...
var leaved = false
$('body').on('mouseover','li',function(){
// ... I omited `setTimeout` to simplify the explanation
leaved = false
jQuery.ajax(
{
// ...
success: function(data){
if (leaved) return;
$('#res').html(data);
}
});
// ...
});
$('body').on('mouseleave', 'li', function() {
// ...
leaved = true
});
I don't understand the use of stop() element in jquery.
In this example, i try to open a div when the user launch the myfunction function (for example by clicking on a trigger)
But if you click several time, #mydiv desapears anyway, without waiting 3 seconds, because it close 3 second after your first click.
function myfunction(hello)
{
$( "#mycontener" ).html( hello );
$( "#mydiv" ).stop( true, true ).slideDown( 250, function() {
setTimeout(function() {
$("#mydiv").slideUp( 250 );
}, 3000);
});
};
Is it clear enough ?
Thanks
You will need to clear the timeout to prevent it from happening on future calls. Something like this:
(function () {
var handle;
function myfunction(hello) {
clearTimeout(handle);
$("#mycontener").html(hello);
$("#mydiv").stop(true, true).slideDown(250, function () {
handle = setTimeout(function () {
$("#mydiv").slideUp(250);
}, 3000);
});
}
window.myfunction = myfunction;
})();
This is my current code to run the series of setTimeout functions. How do I stop these when either the mouse moves, or is over a certain element?
$( document ).ready(function() {
clicky()
function clicky() {
setTimeout(function () {jQuery('#1500').trigger('click');}, 3000);
setTimeout(function () {jQuery('#1990').trigger('click');}, 6000);
setTimeout(function () {jQuery('#2010').trigger('click');}, 9000);
setTimeout(function () {jQuery('#battle').trigger('click');}, 12000);
setTimeout(function () {
jQuery('#water').trigger('click');clicky()
}, 15000);
}
});
You essentially need to save a reference to your timeouts so that they can be cleared when you need them to be. In the following example, I just used an object so that you could specify which timeout you wanted to affect, if desired.
Here's a working fiddle that will clear the timeouts on hover, then reset them when the mouse leaves: http://jsfiddle.net/6tQ4M/2/
And the code:
$(function(){
var timeouts = {};
function setTimeouts () {
timeouts['#1500'] = specifyTimeout('#1500', 3000);
timeouts['#1990'] = specifyTimeout('#1990', 6000);
timeouts['#2010'] = specifyTimeout('#2010', 9000);
timeouts['#battle'] = specifyTimeout('#battle', 12000);
timeouts['#water'] = specifyTimeout('#water', 15000, function(){
console.log('reset the timeouts');
clearTimeouts();
setTimeouts();
});
}
function clearTimeouts () {
for(var key in timeouts){
if(timeouts.hasOwnProperty(key)){
clearTimeout(timeouts[key]);
delete timeouts[key];
}
}
}
function specifyTimeout (id, time, callback) {
return setTimeout(function(){
$(id).trigger('click');
if(callback){
callback();
}
}, time);
}
$('a').on('click', function(){
$('#projects').append('clicky clicky!');
});
$('#map').on('mouseover', clearTimeouts);
$('#map').on('mouseleave', setTimeouts);
setTimeouts();
});
Let me know if you have any questions about the code at all!
Your setTimeout needs to be defined to a variable, so that it can be cleared by passing to clearTimeout(). Something like:
var interval = setTimeout(function() {
//msc
}, 8000);
window.clearTimeout(interval);
Well, according to what you ordered, when you hover an area, the setTimeOut should be fired, and when you are out of this region, the setTimeOut should be reset.
This is the code:
HTML
<div id="map"></div>
CSS
#map{
width:100px;
height:100px;
background-color: black;
}
Javascript
var timeoutHandle;
$('#map').mouseover(function(event){
window.clearTimeout(timeoutHandle);
});
$('#map').mouseout(function(event){
timeoutHandle = window.setTimeout(function(){ alert("Hello alert!"); }, 2000);
});
Basically you should keep a reference to the setTimeOut, in this case the variable is timeoutHandle, call clearTimeOut on mouse over and call setTimeOut again to reset the timer.
Here is the jsFiddle:
http://jsfiddle.net/bernardo_pacheco/RBnpp/4/
The same principle can be used for more than one setTimeOut timer.
You can see more technical details here:
Resetting a setTimeout
Hope it helps.
I am working on a nested menu, and when my mouse move over a option, a sublist will show up.
Here is my hover function:
$( ".sublist" ).parent().hover( function () {
$(this).toggleClass("li_hover",300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
Now, I want add a short period before the sublist shows up to prevent the crazy mouse moving from user. Does somebody have a good suggestion on this?
Update:
Thanks for you guys, I did a little bit change on my program, recently it looks like this:
function doSomething_hover (ele) {
ele.toggleClass("li_hover",300);
ele.find(".sublist").toggle("slide", {}, 500);
}
$(function () {
$( ".sublist" ).parent().hover( function () {
setTimeout(doSomething_hover($(this)), 3000);
});
}):
This is weird that setTimeout will not delay anything. but if I change the function call to doSomething_hover (without "()"), the function will delay good. but i can not pass any jquery element to the function, so it still not works, could somebody tell me that how to make doSomething_hover($(this)) work in setTimeout ?
Update 2:
Got the setTimeout work, but it seems not what I want:
What I exactly want is nothing will happen, if the mouse hover on a option less than 0.5sec.
Anyway, here is the code I make setTimeout work:
function doSomething_hover (ele) {
ele.toggleClass("li_hover",300);
ele.find(".sublist").toggle("slide", {}, 500);
}
$(function () {
$( ".sublist" ).parent().hover( function () {
var e = $(this);
setTimeout(function () { doSomething_hover(e); }, 1000);
});
}):
Final Update:
I got this work by using clearTimeout when I move the mouse out.
so the code should be:
$( ".sublist" ).parent().mouseover( function () {
var e = $(this);
this.timer = setTimeout(function () { doSomething_hover(e); }, 500);
});
$( ".sublist" ).parent().mouseout ( function () {
if(this.timer){
clearTimeout(this.timer);
}
if($(this).hasClass("li_hover")){
$(this).toggleClass("li_hover");
}
$(this).find(".sublist").hide("slide", {}, 500);
});
This is the part in the $(document).ready(). Other code will be same as above.
真. Final Update:
So, mouseover and mouseout will lead to a bug sometime, since when I move the mouse to the sublist, the parents' mouseover event will be fire, and hide the sublist.
Problem could be solved by using hover function:
$( ".sublist" ).parent().hover(
function () {
var e = $(this);
this.timer = setTimeout(function () { doSomething_hover(e); }, 500);
},
function () {
if(this.timer){
clearTimeout(this.timer);
}
$(this).find(".sublist").hide("slide", {}, 500);
if($(this).hasClass("li_hover")){
$(this).toggleClass("li_hover",300);
}
}
);
Thanks all
Try this please:
Code
setInterval(doSomthing_hover, 1000);
function doSomthing_hover() {
$(".sublist").parent().hover(function() {
$(this).toggleClass("li_hover", 300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
}
SetTime vs setInterval
At a fundamental level it's important to understand how JavaScript timers work. Often times they behave unintuitively because of the single thread which they are in. Let's start by examining the three functions to which we have access that can construct and manipulate timers.
var id = setTimeout(fn, delay); - Initiates a single timer which will call the specified function after the delay. The function returns a unique ID with which the timer can be canceled at a later time.
var id = setInterval(fn, delay); - Similar to setTimeout but continually calls the function (with a delay every time) until it is canceled.
clearInterval(id);, clearTimeout(id); - Accepts a timer ID (returned by either of the aforementioned functions) and stops the timer callback from occurring.
In order to understand how the timers work internally there's one important concept that needs to be explored: timer delay is not guaranteed. Since all JavaScript in a browser executes on a single thread asynchronous events (such as mouse clicks and timers) are only run when there's been an opening in the execution.
Further read this: http://ejohn.org/blog/how-javascript-timers-work/
timeout = setTimeout('timeout_trigger()', 3000);
clearTimeout(timeout);
jQuery(document).ready(function () {
//hide a div after 3 seconds
setTimeout( "jQuery('#div').hide();",3000 );
});
refer link
function hover () {
$( ".sublist" ).parent().hover( function () {
$(this).toggleClass("li_hover",300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
});
}
setTimeout( hover,3000 );
....
You could use .setTimeout
$(".sublist").parent().hover(function() {
setTimeout(function() {
$(this).toggleClass("li_hover", 300); //use to change the background color
$(this).find(".sublist").toggle("slide", {}, 500); //sub list show / hide
}, 1000);
});
i have a jquery function that when clicked produces a set timeout on making a div visible.
however, if another option is selected during the settimeout length, i would like to know how to destroy this function and stoop anything else in it happening.
my current code is:
$(document).ready(function () {
$('li#contact').click(function () {
$('ul.image_display').css('display', 'none');
$('ul.projects').fadeOut().hide();
$('li#cv').removeClass('cur');
$('li#projects').removeClass('cur');
$('li#contact').addClass('cur');
$('ul.contact').fadeIn(function () {
setTimeout(function () {
$('ul.contact').fadeOut('slow');
}, 8000);
});
setTimeout(function () {
$('li#contact').removeClass('cur');
$('li#cv').addClass('cur');
$('ul.projects').fadeIn('slow');
$('ul.image_display').css('display', 'block');
}, 8625);
});
});
a bit cumbersome but works until this is clicked:
$(document).ready(function () {
$('#projects').click(function () {
$('li#cv').removeClass('cur');
$('ul.contact').fadeOut().hide();
$('#contact').removeClass('cur');
$('ul.projects').fadeIn('slow');
$('#projects').addClass('cur');
$('ul.image_display').css('display', 'block');
});
});
if the second is clicked just after the first than class 'cur' still comes up on li#cv after the set time.
The setTimeout function returns an identifier to that timeout. You can then cancel that timeout with the clearTimeout function. So you can do something like this (fill in the blanks with your code):
var timer;
$(function() {
$(...).click(function() {
...
timer = setTimeout(...);
...
});
$(...).click(function() {
clearTimeout(timer);
});
});
It's not particularly super clean to keep a global variable for this, however. You could store the timer in the data attribute of whatever element makes the most sense for your situation. Something like this:
$(function() {
$(...).click(function() {
...
var timer = setTimeout(...);
$(someelement).data('activetimer', timer);
...
});
$(...).click(function() {
var timer = $(someelement).data('activetimer');
if(timer) {
clearTimeout(timer);
$(someelement).removeData('activetimer');
}
});
});
It doesn't really look cleaner, but it's an alternative way to store the timer...
You can use clearTimeout() to do that. You'll need to keep the return value from setTimeout() in a variable to pass to clearTimeout().