How do I slow down the execution of a jquery click function? - javascript

I use a simple jquery command in the Google Chrome console to manage my site. Basically, I have to approve a number of new requests every day, so I use:
$('.approve').click();
where 'approve' is the class name of the button that needs to get clicked. This saves me hours. However, this crashes my browser every time, and sometimes doesn't work, mainly because of the resource taxing it put on my laptop. I was looking for a way to slow down the actions of the function. I tried...
$('.approve').click().delay(1000);
to try and slow it down by 1 second between button clicks. This didn't seem to work (it ran without errors but I don't think it slowed down the clicking.
Any ideas?
Edit:
Someone pointed out that this may be a duplicate of another question. The reason it isn't is that the other top answer focuses on using JS to define a function that uses setTimeout(), where I am looking for a native jquery method of doing it. I understand jquery is written in JS, but because I'm using it in a command console, I don't have the luxury of multiple lines of coding space.
Can anyone also tell me why the above function wouldn't work? It seems like it should, based on my research.
Thank you in advance.

Wait 1 second between each click:
You will need to iterate over each .approve-button, then trigger the click event for each button with a second in between: (setTimeout)
$('.approve').each(function(index) {
var $approve = $(this);
setTimeout(function() {
// Simulation click event
$approve.trigger('click');
// 0, 1, 2, 3, ... times 1000 to bring delay to miliseconds
}, index * 1000);
});
One liner (For IE9+):
$(".approve").each(function(c){setTimeout(function(c){c.click()},1e3*c,$(this))});
One liner:
$(".approve").each(function(e){var i=$(this);setTimeout(function(){i.click()},1e3*e)});

You can add a delay on the function click like so
$(".approve").click(function(){
setTimeout(function(){
// Do something
}, 1000);
});

If you want to exectue your function once, use setTimeout()
$(".approve").click(function(){
setTimeout(function(){
}, 1000);
});
If you want to exectue it every second, use setInterval()

when click you have to run a function that will execute setTimeout function
$('.approve').click(function(){
setTimeout(function(){
// here some code u want to execute after 5 sec //
}, 5000);
});

Related

setTimeout blocking issue

I'm writing a "Game of Life" in javascript. I have all the logic done in a function called doGeneration(). I can repeatedly call this from the console and everything goes as planned, however, if I put it in a while loop the execution blocks the UI and I just see the end result (eventually).
while (existence) {
doGeneration();
}
If I add a setTimeout(), even with a generation limit of say 15, the browser actually crashes (Canary, Chrome).
while (existence) {
setTimeout(function() {
doGeneration();
},100);
}
How can I call doGeneration() once every second or so without blocking the DOM/UI?
You want setInterval
var intervalId = setInterval(function() {
doGeneration();
}, 1000);
// call this to stop it
clearInterval(intervalId);
I would use requestAnimationFrame(doGeneration). The idea of this function is to let the browser decide at what interval the game logic or animation is executed. This comes with potential benefits.
https://hacks.mozilla.org/2011/08/animating-with-javascript-from-setinterval-to-requestanimationframe/
Rather than using setINterval or setTimeout and assume some random time interval will be enough for the UI to update you shoul/could make the doGeneration smart enough to call itself after dom was updated and if the condition of existence is satisfied.

Jquery or Javascript Animating the Z-Index

I need the functionality of animating the z-index property of a specific HTML object. I've been able to achieve this animation in two ways that both have their difficulties/drawbacks. Successfully answering this question for me will fix one of the following two issues:
The first is by adapting the JQuery animate command with the step functionality outlined here by the accepted answer:
jQuery's $('#divOne').animate({zIndex: -1000}, 2000) does not work?
The problem with this method for me is that the $('#obj').stop(); command cannot prematurely end the animation when done in this way. It always finishes unless I destroy the object I'm working with and create a new one (which causes blinking obviously). If anyone knows of a way to properly stop a step animation like this, or a work-around for the issue, I'd love to see it.
var div = $('#obj');
$({z: ~~div.css('zIndex')}).animate({z: [-2000, 'linear']}, {
step: function() {
div.css('zIndex', ~~this.z);
},
duration: 10000
});
The second is using a setInterval loop on 20 MS (a speed that is sufficient for my needs) to simply adjust the z-index to what it should be at that point of the "animation". This works great for a few moments, then something causes it to stop working suddenly. The code still runs through the $('#obj').css('z-index', val); line, and val is changing, but it no longer updates the object in the DOM. I've tried it on slower timer settings as well with identical results. Anyone know why JQuery might suddenly no longer be able to set the Z-Index?
function () move {
if (!(MoveX == 0 && MoveY == 0))
{
$('#obj').css('z-index', val);
}
}
$('#obj').stop() doesn't work for you because the animation isn't being performed on $('#obj').
It is being performed on the object $({z: ...}) (with a custom step function). This means you should do something like
var anim = $({z: ~~div.css('zIndex')}).animate({z: [-2000, 'linear']}, {
step: function() {
div.css('zIndex', ~~this.z);
},
duration: 10000
});
// sometime later
anim.stop();
See this demo.
Edit For what it's worth, here is the same demo using an animation interval. I see a syntax error in your second snippet: the function declaration should be
function move() { ...
I assume that's a typo since your code wouldn't even parse. Other than that, I'm not sure why that solution didn't work for you.

javascript setInterval not keeping it's timing properly

I've got multiple elements on my page that fade in and out on a timer using javascript setInterval to set them in motion. I have them delayed so they are offset just slightly to create a nice cascading effect, but if you leave the page open long enough, they all catch up to one another and the timing gets all messed up (you've got to leave it for a few minutes).
I have an ugly example of the issue at CodePen here: http://www.cdpn.io/wgqJj
Again, you've got to leave the page open and untouched for a few minutes to see the problem. If you had more items on the page (5 or 10) the problem becomes even more apparent. I've also used this type of effect with several jQuery photo rotator plugins, and over time, the issue always crops up.
Is there any explanation for this?
Here is the code I'm using (I know the javascript could be cleaner):
HTML:
<p id="one">First</p>
<p id="two">Second</p>
<p id="three">Third</p>
JavaScript:
$(document).ready(function() {
var timer1 = setTimeout(startOne,1000);
var timer2 = setTimeout(startTwo,2000);
var timer3 = setTimeout(startThree,3000);
});
function startOne () {
setInterval(flashOne,3000);
}
function startTwo () {
setInterval(flashTwo,3000);
}
function startThree () {
setInterval(flashThree,3000);
}
function flashOne () {
$("#one").fadeTo("slow",0.4).fadeTo("slow",1.0);
}
function flashTwo () {
$("#two").fadeTo("slow",0.4).fadeTo("slow",1.0);
}
function flashThree () {
$("#three").fadeTo("slow",0.4).fadeTo("slow",1.0);
}
Question has already been answered here. Quoting from the top rated answer in this topic:
it will wait AT LEAST 1000MS before it executes, it will NOT wait exactly 1000MS.
Giving an actual answer, I'd solve it like this:
$(function(){
setTimeout(flashOne,1000);
});
function flashOne () {
$("#one").fadeTo("slow",0.4).fadeTo("slow",1.0);
setTimeout(flashTwo,1000);
}
function flashTwo () {
$("#two").fadeTo("slow",0.4).fadeTo("slow",1.0);
setTimeout(flashThree,1000);
}
function flashThree () {
$("#three").fadeTo("slow",0.4).fadeTo("slow",1.0);
setTimeout(flashOne,1000);
}
Like this it's not possible for the timers to mess up, as it's always delayed one second after the item before has flashed.
Consider using a chained setInterval instead as this give a guaranteed slot to the browser. Reference this SO post..
Currently you only use setInterval to start the animation. From there jQuery is handling the "oscillations".
Theoretically using a chained set interval should guarantee a slot, to the browser. More importantly, you can hard code the offset into the code at each interval, instead of only once at the beginning.
The setTimeout() and setInterval() functions do not guarantee that your events run exactly on schedule. CPU load, other browser tasks, and similar can and will affect your timers, therefore they are not reliable enough for your use case.
A solution for this would be asynchronous events (promises or similar) or using the event queue that jQuery supplies. That way you could either nest with callbacks, or queue them up and then fire the queue over again once it hits the last item in the queue. The .queue() API documentation page has an example of this.

How do I add a load icon to a page that just processes javascript code?

I use Ajax load icons all the time for when I do ajax requests.
I want to know if it's possible to accomplish the same thing with just regular javascript code. For example:
$('button').on('click', function(){
showLoadingBar();
longProcess();
hideLoadingBar();
});
longProcess() is just a function that can take 1-3 seconds to process (it does a lot of calculations and manipulates the DOM but doesn't do any ajax requests).
Right now, the browser halts/freezes during these 1-3 seconds, so what I would rather do is show a loading icon during this time. Is this possible? The code I have above pretty much ignores showLoadingBar().
The DOM won't be updated until the current Javascript process ends, so you can't do it just like that. You can however use setTimeout to get around that:
showLoadingBar();
setTimeout(function() {longProcess(); hideLoadingBar(); }, 1);
What happens above, in case it isn't clear, is that showLoadingBar is executed, then a timeout is set up. The current process will then end and allow the DOM to update with the loading bar, before the timeout is invoked, very shortly after. The handler executes your heavy function and when it's done, hides the loading bar again.
The following will give you control over the action on click. What this means is you can disable the clicking ability till it has finished running. But also i've including setTimeout which returns control to the browser (thus removing that annoying "lockup" feeling) and in the timeout function we preform our long process then re-enable the button! VIOLA!
function startProc() {
var $this = $(this);
$this.off("click", startProc);
showLoadingBar();
setTimeout(function() {
longProcess();
hideLoadingBar();
$('button').on('click', startProc);
});
}
$('button').on('click', startProc);
Dude,
Use the .bind method, which in this case is performed so:
$('button').bind('click', function(){
showLoadingBar();
longProcess();
hideLoadingBar();
});

Show a message box which slides out, delays for 3 seconds and slides in with Mootools?

I'm creating a error message displaying box which slides out, delays for 3 seconds and then slides in with Mootools. This is what I'm currently doing now, how can I correct it to get it work for me?
var slide = new Fx.Slide($("error"));
slide.slideOut('horizontal').chain(function(){
$("error").set("text", message);
}).chain(function(){
this.slideIn('horizontal').delay(3000);
}).chain(function(){
this.slideOut('horizontal');
});
You basically have your mootools correct, but are missing a few key items that would make your script function properly. I have pasted a working version below, and then made some comments:
var slide = new Fx.Slide($("error"));
slide.slideOut('horizontal').chain(function () {
$('error').set('text', message); this.callChain(); //NOTE
}).chain(function () {
this.slideIn('horizontal');
}).chain(function () {
this.slideOut.delay(3000, this, 'horizontal'); //NOTE
});
Notice the this.callChain() on the
3rd line. Not having this was what
was stopping you seeing anything.
The Fx class uses the callChain()
method internally to start the next
step in the sequence, but if your
argument to chain() doesn't contain
one of Fx's methods, callChain() is
not called, so you have to do it
manually.
Your call to delay was in the wrong place. Delay() delays the execution of the function it is applied to, it does not insert a pause into a chain. Therefore to display the error message for 3sec you need to add delay to the the last function call, because this is the one you want to slow down
Your call to delay was incorrect. Delay applies to the function, not the return value of the function, hence Dimitar's suggestion above. Have a look at function in the mootools core documentation for more info
By the sounds of it, you do not have firebug installed. This would have let you explore the DOM to find that your code changes the margins and then the text, but nothing happens after that. Firebug is super useful, so install it ASAP
My solution (mootools 1.3) is below, and basically relfects what dimitar was suggesting:
$('error').set('slide', {
mode: 'horizontal'
}).get('slide').slideOut().chain(function () {
$('error').set('text', message); this.slideIn();
}, function () {
this.slideOut.delay(3000, this);
});
Hope it helps

Categories

Resources