How to add .delay to .click on .each iteration (jquery) - javascript

So, I want to put delay on this JavaScript code.
$(function(){
$('.clickThis').each(function(){
$(this).click();
});
});
I tried this
$(function(){
$('.clickThis').each(function(){
$(this).click().delay(5000);
});
});
above script doesnt work .
Is there any alternative?
I've tried Google it but I still couldn't figure it out, because I have little knowledge in JavaScript.

This will do it:
$(function(){
$('.clickThis').each(function(i, that){
setTimeout(function(){
$(that).click();
}, 5000*i );
});
});

Here's a version using a recursive setTimeout loop.
$(function() {
var click = $('.clickThis').toArray();
(function next() {
$(click.shift()).click(); // take (and click) the first entry
if (click.length) { // and if there's more, do it again (later)
setTimeout(next, 5000);
}
})();
});
The advantage of this pattern over setTimeout(..., 5000 * i) or a setInterval call is that only a single timer event is ever queued at once.
In general, repeated calls to setTimeout are better than a single call to setInterval for a few reasons:
setInterval calls can queue up multiple events even if the browser isn't active, which then all fire as quickly as possibly when the browser becomes active again. Calling setTimeout recursively guarantees that the minimum time interval between events is honoured.
With setInterval you have to remember the timer handle so you can clear it

You need to write an asynchronous setTimeout loop, for more information http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

Try to use this:
$(function () {
var items=$('.clickThis');
var length=items.length;
var i=0;
var clickInterval=setInterval(function(){
items.eq(i).click();
i++;
if(i==length)
clearInterval(clickInterval);
}, 5000);
});

var $clickthis=$(".clickthis");
var i= -1;
var delayed = setInterval(function(){
if (++i < $clickthis.length) $clickthis.eq(i).trigger("click");
else clearInterval(delayed);
}, 5000);

I am not sure but I think that setTimeout function should do the trick.
See here https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout

Try
$(function(){
$('.clickThis').each(function(_,i){
var me=$(this);
setTimeout(function(){me.click()},5000*i);
);
});

Related

How to append data only one time after click with jQuery

So, i have this little function:
carousel_controls_buttons.live('click', function(e){
setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});
What i'm trying to do is stop appending info_board_description more then one time after two, three fast clicks. When i do this this data appends more than one time and i have content duplication. How can i stop this for some time, f.e. this 450ms? Thx for help.
Use a boolean to control it.
var flag = true;
carousel_controls_buttons.live('click', function(e){
e.preventDefault();
if (flag) {
setTimeout(function(){
info_board_span.append(info_board_description);
flag = true;
}, 450);
flag = false;
}
});
You can use clearTimeout function:
var t = '';
carousel_controls_buttons.live('click', function(e){
clearTimeout(t);
t = setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});
example: http://jsfiddle.net/xhSvC/
Note that live method is deprecated, you should use on method instead.
While the other answers ought to work, I would like to introduce you to the concept of debounce & throttle.
http://benalman.com/projects/jquery-throttle-debounce-plugin/ is one plugin you may use to achieve what you need, ie, ensure a function is executed only once per x seconds.
Throttle versus debounce
Both throttling and debouncing will rate-limit execution of a
function, but which is appropriate for a given situation?
Well, to put it simply: while throttling limits the execution of a
function to no more than once every delay milliseconds, debouncing
guarantees that the function will only ever be executed a single time
(given a specified threshhold).
carousel_controls_buttons.live('click', function(e) {
$.debounce(450, function() {
info_board_span.append(info_board_description);
e.preventDefault();
});
});
Put an count over there say var count=0; increment when hit and check for the condition if count==1 append it if not leave it
There is a one event for achieve this:
carousel_controls_buttons.one('click', function() {
setTimeout(function(){
info_board_span.append(info_board_description);
e.preventDefault();
}, 450);
});

Stopping a running function in javascript/jquery on click event

I have a slideshow function in jquery that I want to stop on a particular click event. The slideshow function is here:
function slider(){
setInterval(function(){
var cur = $('img.active');
cur.fadeOut('fast');
cur.removeClass('active');
cur.css('opacity','0');
cur.addClass("hidden");
var nextimg;
if (!cur.hasClass("last")){
nextimg = cur.next("img");
}
else {
nextimg = cur.prev().prev().prev();
}
nextimg.removeClass("hidden").fadeIn('slow').css('opacity','1').addClass('active');
},5000);
}
I have been reading about .queue but not sure how I can use it exactly, can I call my function from a queue and then clear the queue on a click event? I cannot seem to figure out the syntax for getting it to work of if thats even possible. Any advice on this or another method to stop a running function on a click would be appreciated.
For what it's worth, it's generally advisable to use a recursive setTimeout instead of a setInterval. I made that change, as well as a few little syntax tweaks. But this is a basic implementation of what I think you want.
// Store a reference that will point to your timeout
var timer;
function slider(){
timer = setTimeout(function(){
var cur = $('img.active')
.fadeOut('fast')
.removeClass('active')
.css('opacity','0')
.addClass('hidden'),
nextimg = !cur.hasClass('last') ? cur.next('img') : cur.prev().prev().prev();
nextimg.removeClass('hidden')
.fadeIn('slow')
.css('opacity','1')
.addClass('active');
// Call the slider function again
slider();
},5000);
}
$('#someElement').click(function(){
// Clear the timeout
clearTimeout(timer);
});
Store the result of setInterval in a variable.
Then use clearInterval to stop it.
Store the value returned by setInterval, say intervalId to clear it, your click handler should look like this:
function stopSlider() {
//prevent changing image each 5s
clearInterval(intervalId);
//stop fading the current image
$('img.active').stop(true, true);
}

In JQuery, Is it possible to get callback function after setting new css rule?

I have $('.element').css("color","yellow") and I need that next event was only after this one, something looks like $('.element').css("color","yellow",function(){ alert(1); })
I need this because:
$('.element').css("color","yellow");
alert(1);
events are happen at one time almost, and this moment call the bug in animation effect (alert(1) is just here for example, in real module it's animation)
you can use promise
$('.element').css("color","yellow").promise().done(function(){
alert( 'color is yellow!' );
});
http://codepen.io/onikiienko/pen/wBJyLP
Callbacks are only necessary for asynchronous functions. The css function will always complete before code execution continues, so a callback is not required. In the code:
$('.element').css('color', 'yellow');
alert(1);
The color will be changed before the alert is fired. You can confirm this by running:
$('.element').css('color', 'yellow');
alert($('.element').css('color'));
In other words, if you wanted to use a callback, just execute it after the css function:
$('.element').css('color', 'yellow');
cb();
You can use setTimeout to increase the sleep time between the alert and the css like this:
function afterCss() {
alert(1);
}
$('.element').css("color","yellow");
setTimeout(afterCss, 1000);
This will make the alert appear 1 second after the css changes were committed.
This answer is outdated, so you might want to use promises from ES6 like the answer above.
$('.element').css("color", "yellow").promise().done(function(){
// The context here is done() and not $('.element'),
// be careful when using the "this" variable
alert(1);
});
There's no callback for jquery css function. However, we can go around, it's not a good practice, but it works.
If you call it right after you make the change
$('.element').css('color','yellow');
alert('DONE');
If you want this function has only been called right after the change, make an interval loop.
$('.element').css('color','yellow');
var detectChange = setInterval(function(){
var myColor = $('.element').css('color');
if (myColor == 'yellow') {
alert('DONE');
clearInterval(detectChange); //Stop the loop
}
},10);
To avoid an infinite loop, set a limit
var current = 0;
$('.element').css('color','yellow');
current++;
var detectChange = setInterval(function(){
var myColor = $('.element').css('color');
if (myColor == 'yellow' || current >= 100) {
alert('DONE');
clearInterval(detectChange); //Stop the loop
}
},10);
Or using settimeout as mentioned above/
use jquery promise,
$('.element').css("color","yellow").promise().done(function(){alert(1)});

clearTimeout not working in javascript autocomplete script

I am using the following code as part of an autocomplete script to avoid hammering the server with every keystroke:
var that = this;
textInput.bind("keyup", function() {
clearTimeout(that.timer);
that.timer = setTimeout (that.doStuff(), 2000);
});
Unfortunately, this does not clear the old timers. They still all execute.
Does anyone know what I'm missing?
Thanks!
You probably want to use:
that.timer = setTimeout (that.doStuff, 2000);
instead of:
that.timer = setTimeout (that.doStuff(), 2000);
Otherwise, doStuff will be called immediately.

Call js-function using JQuery timer

Is there anyway to implement a timer for JQuery, eg. every 10 seconds it needs to call a js function.
I tried the following
window.setTimeout(function() {
alert('test');
}, 10000);
but this only executes once and then never again.
You can use this:
window.setInterval(yourfunction, 10000);
function yourfunction() { alert('test'); }
window.setInterval(function() {
alert('test');
}, 10000);
window.setInterval
Calls a function repeatedly, with a
fixed time delay between each call to
that function.
Might want to check out jQuery Timer to manage one or multiple timers.
http://code.google.com/p/jquery-timer/
var timer = $.timer(yourfunction, 10000);
function yourfunction() { alert('test'); }
Then you can control it with:
timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...
setInterval is the function you want. That repeats every x miliseconds.
window.setInterval(function() {
alert('test');
}, 10000);
jQuery 1.4 also includes a .delay( duration, [ queueName ] ) method if you only need it to trigger once and have already started using that version.
$('#foo').slideUp(300).delay(800).fadeIn(400);
http://api.jquery.com/delay/
Ooops....my mistake you were looking for an event to continue triggering. I'll leave this here, someone may find it helpful.
try jQueryTimers, they have great functionality for polling
http://plugins.jquery.com/project/timers
You can use setInterval() method also you can call your setTimeout()
from your custom function for example
function everyTenSec(){
console.log("done");
setTimeout(everyTenSec,10000);
}
everyTenSec();
function run() {
window.setTimeout(
"run()",
1000
);
}

Categories

Resources