Basiaclly I need to set a time out to run 2 functions at two different times and wanted to strucuture it right. What I was looking for is something like this:
setTimeout(function(){
$('body').chardinJs('start');
},3000
);
setTimeout(function(){
$('body').chardinJs('stop');
},6000
);
So it would run one method after 3sec and another after 6sec. Is this correct way or can you chain them together?
This is correct.
However you should have a look on Javascript callbacks or jQuery deferred handlers. Could be cleaner.
Of course.
function sto(el, str, tm){
setTimeout(function(){
$(el).chardinJs(str);
},tm
);
}
sto('body', 'start', 3000);
sto('body', 'stop', 6000);
another would be so much longer (setInterval, [switch] or [if])
Related
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);
});
setInterval(this.Animate(), this.speed);
This is expected to be run every this.speed times. Yes, but the browsers run it only one time. What are the possible reasons for that?
Try to run your function without the parentheses, when you put parentheses it always calls the function instead of passing it, which is what you want here:
setInterval(this.Animate, this.speed);
If it still doesn't work, you should debug and find out what is the scope for 'this', as 'this' might change. You can do that by adding a breakpoint in your browser's JS debugger.
Also, you can try this to avoid the scope problem with 'apply'
var animate = this.animate.apply(this)
setInterval(animate, this.speed);
p.s: It might be a good choice to avoid setInterval for animation as they might queue and then fire at once. Instead call setTimedout once and again at the end of the function (this.Animate) as so to create a loop.
If Animate is a derived function from the prototype, you'll have to use:
setInterval(this.Animate.bind(this), this.speed);
Do the following:
setInterval(this.Animate, this.speed);
You are executing the function instead of assigning a reference to the function to be executed at a certain interval...
Let us look at your code
setInterval(this.Animate(), this.speed);
What it is saying is run the function this.Animate() right away and store what ever it returns to be called.
What you want to do is create a closure
var that = this;
setInterval( function(){ that.Animate() }, this.speed);
The that maintains the current scope.
If you're looking for a JQuery refresh script, try:
refreshId = setInterval(function() {
// Events or Actions
}, 5000);
If you ever want to Pause or Stop this, use clear interval: clearInterval(refreshId);.
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)});
Whats wrong in here?
$(document).ready(function(){
$(window).load(function(){$("#welcome").fadeIn(2000); })
setTimeout(function(){
$('div#welcome').fadeOut(2000);
}, 4000);
setTimeout(function(){
$('div#content').fadeIn(2000);
}, 6000);
setTimeout(function(){
$('div#menu').fadeIn(2000);
}, 8000);
});
It seems like something is not running as it should, as all functions will be called parallel.
In addition people tell me that my graphic will be loaded with a delay and will 'stick'.
I appreciate any help!
So, syntax-wise, there isn't a semi-colon at the end of the window.load event setter. You should add that.
However, I just ran your JS with a mock HTML set, and it worked fine. Not sure what you are experiencing. All three of the setTimeout calls will begin to run at the same time. So... rather than taking 18 seconds to run, they will all only take 8 seconds to run. It looks like that is what you wanted.
Here is the most efficient wait to write your code though:
$(document).ready(function(){
$(window).load(function(){
$("#welcome").fadeIn(2000).delay(2000).fadeOut(2000,function(){
$('div#content').fadeIn(2000,function(){
$('div#menu').fadeIn(2000);
});
});
});
});
Here, what will happen is that each of your animations will trigger the next animation, when they are complete.
I think you are looking for something like this.
$(document).ready(function(){
$("#welcome").fadeIn(2000, function(){
setTimeout(function(){
$('div#welcome').fadeOut(2000, function(){
setTimeout(function(){
$('div#content').fadeIn(2000, function(){
setTimeout(function(){
$('div#menu').fadeIn(2000);
}, 8000);
});
}, 6000);
});
}, 4000);
});
});
If you want to do something after something is finished you need to add another function after you set your parameter (2000 in this case).
I believe that you want to do something like this http://jsfiddle.net/Cp4Dx/
OP don't forget about Jquery's delay() function which can help you avoid setTimeout().
$(window).load(function(){$("#welcome").fadeIn(2000).delay(4000).fadeOut(2000)});
You can use the jQuery queue for it:
$(document).ready(function() {
$('#welcome').fadeIn(2000).delay(2000).fadeOut(2000);
$('#content').delay(4000).fadeIn(2000);
$('#menu').delay(6000).fadeIn(2000);
});
Demo: http://jsfiddle.net/ThiefMaster/9nPAR/
I have some code, with the order of the functions in the order I want them executed. However, they seem to at the same time (they begin sequentially within microseconds of eachother presumably).
The problem is that some of the functions include animations. How do I make it so the next function doesn't execute until the previous functions are completely finished???
Following is some of my code. I created a callback chain thinking that it would be the solution, but indeed it is not. The functions themselves call jQuery animations. I'm guessing i need to use some type of notofication from jQuery to tell me when animations are done. Anyhow, any advice is greatly appreciated!
show_loader(0, function() {
close_box($target_close, '/', '#' + $target_close.attr('id') + ' .post_wrap', function() {
open_box($target_open, event.value, '.wide-col', function() {
hide_loader(function() {
scroll_to_content($target_open, function() {
});
});
});
});
});
To be precise, I want the scroll_to_content() function to be executed after all the previous actions have been completed in their entirety. Currently, it executes at the same time as everything else, and therefore my page scroll is completely off because the size of my content continues changing after scroll_to_content() is finished.
Callback chains are basically the solution but I suspect you're not threading your callbacks correctly in your calls to jQuery. $.animate(...) has an optional complete callback-- that's where you want to pass the function that should execute after your initial animation finishes. All of the Effects in jQuery UI should have a similar optional argument.
You can use a similar pattern yourself in order to chain event handlers, for instance:
function handler(event, callback) {
// do some work
// ...
callback();
}
This strategy for chaining function evaluations is called continuation-passing style and is handy in a lot of situations. Be careful using it, however, as many people find it more confusing to read than a traditional, sequential implementation.
http://api.jquery.com/queue/
Sorry, I don't have enough time to go into detail, but as the previous commenter said, queues are what you want to be focusing on to solve this problem.
you have 3 options:
1- Split your animations into multiple chained animate() calls.
This is an example to clarify it for you.
2- Follow the answer posted by #dml.
3- Try to use this plugin to add delays between your calls (don't know if it can fix this scenario or not, give it a try)
http://www.evanbyrne.com/article/jquery-delay-plugin