jquery delay between javascript functions - javascript

I have multiply functions with parameters simplified as:
function f1(p1,p2){
alert('Function one is P1:'+p1+' P2:'+p2);
}
function f2(p1,p2){
alert('Function two is P1:'+p1+' P2:'+p2);
}
I need to fire these is a sequence with a delay between. I have however found that jQuery dislikes running functions with parameters. I have tried the .click function.
$.delay(1000).click(f1('One',false)).delay(1000).click(f2('One',false));
But the delay makes the click functions not work...

I would just use a simple timeout:
f1("one", false);
setTimeout(function() { f2("one", false); }, 1000);

$.delay(1000).click(function(){f1('One',false);}).delay(1000).click(function(){f2('One',false);});
not sure what the click is for though ...

if you want to delay a function call then a much simpler way is to use setTimeout().
eg:
// calling it in a nested setTimeout for sequential delayed execution
setTimeout(function(){
f1('One',false);
setTimeout(function(){
f1('One',false)
},300)
},300)

function fn1()
{
alert(1);
}
function fn2()
{
alert(2);
}
var arr=[fn1,fn2];
var len=arr.length;
var time=1000;
for(var k=0;k<len;k++)
{
(function(k)
{
setTimeout(arr[k],time);
}(k))
time=time*2;
}
It executes after a delay of 1 second!
DEMO

Related

Javascript - Disable all nested functions for some time after one function function has been executed

After a function has run I want to disable a whole set of functions can be executed again. I thought the most logical way would be to put them all together inside an overarching function (in this case function run) and disable that function for some time.
So for example in the code below, when function exampleOne is executed I want to disable the whole run function for X time before it can run again.
function run(){
function exampleOne(){
// Code
sleep(1000);
}
function exampleTwo(){
// Code
sleep(1000);
}
}
run();
Take a look at underscore.js and especially the throttle or debounce functions.
You can define your functions as variables then you can disable them by assigning an empty or error functions to these variables. Two functions (e.g. enable/disable) can be responsible to disable/enable the whole set of functions. and of course you can use setTimeout to manage the delay.
for example:
var exampleOne, exampleTwo;
function enable(){
exampleOne = function(){
// do something
disable();
setTimeout(function() { enable(); }, 10000);
}
exampleTwo = function(){
// do something
disable();
setTimeout(function() { enable(); }, 10000);
}
}
function disable(){
exampleOne = function(){
Alert("i'm sleep!")
}
exampleTwo = function(){
// do nothing
}
}
enable();

javascript setTimeout function does not work

I am trying to update a variable every one second. For that reason I am using setTimeout. But it does not update the variable. It logs out 0 just once. Here is my code
var yes=0;
setTimeout(function () {
console.log(yes);
yes++;
}, 1000);​
Use setInterval, to finish the repitition you have to clear the interval using clearInterval(yourInterval);
Live Demo
var yes=0;
yourInterval = setInterval(function () {
console.log(yes);
yes++;
}, 1000);​
setTimeout does repeat itself only once, try setInterval so that for every second it increments yes with 1
but remember to clear the interval after sometime else you get on to a never ending loop
using clearInterval()
setTimeOut method is just called once after a specific timeout which in your case is 1000, try to use setInterval method instead
jsBin demo with setTimeout
If you really want to stick to setTimeout (I appreciate that ;) )
than just wrap all into a function and recall it inside it self like:
var yes=0;
(function loop(){
setTimeout(function () {
console.log(yes);
yes++;
loop(); // loop recall
}, 1000);
})();
Otherwise go for setInterval:
var yes=0;
function count(){
console.log(yes);
yes++;
}
setInterval(count, 1000);

How to clear a javascript timeout thats set within a function

I have a recursive type function in Javascript that runs like this:
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Note: I've simplified the function to make it easier to read.
I have "a" tags called like this
Load thumb 3
However, they don't clearout the timer, the timer continues to cycle through the function irregardless of the clearTimeout() being called.
Any ideas why? I think it might have something to do with a scope problem or something like that.
Yeah, you need to make rotate a global variable. Simply declare it outside the function like so:
var rotate;
var delay = 1000;
function loadThumb(thumb) {
alert("loading thumb: " + thumb);
rotate = setTimeout(function() {
loadThumb(thumb + 1);
}, delay);
}
Also, you need to make sure you clear the timeout before you call loadThumb. Otherwise you'll clear the timer you just started.
Load thumb 3
fiddle: http://jsfiddle.net/63FUD/
it may be the issue of scope so make rotate as global variable and call clearTimeout(rotate);
refer clearTimeout() example
It may be a scoping issue if you are not declaring rotate externally.
Try this:
var rotate = 0;
function loadThumb(thumb) {
rotate=setTimeout(function() {
loadThumb(next);
}, delay);
}
Return false on the link
Since you are not using var rotate, it should not be a scoping issue since rotate would be in the window scope. Can you show the complete code?
It is considered poor coding to inline the script - you should attach the event handler onload of the page
Also you should not have the setTimeout inside a function that might be called for one image
Try this:
var rotate,next=1;
function loadThumb(thumb) {
if (thumb) ... use thumb
else ... use next
}
function slide() {
rotate=setInterval(function() {
loadThumb();
next++;
if (next>=images.length) next=0;
}, delay);
}
window.onload=function() {
var links = document.getElementsByTagName("a");
if (links[i].className==="thumbLink") {
links[i].onclick=function() {
var idx = this.id.replace("link","");
loadThumb(idx);
clearInterval(rotate);
return false;
}
}
document.getElementById("start").onclick=function() {
slide();
return false;
}
document.getElementById("stop").onclick=function() {
clearInterval(rotate);
return false;
}
slide();
}
assuming
Start
Stop
Show 1
Show 2
Show 3
If you have to manage multiple timeouts, you can use an object in the global scope and some custom methods to create and remove your timeouts. To access the methods you can either put the calls in the onclick handler of your links (like in the example), or use a library like jQuery to bind them.
<script type="text/javascript">
var timeouts = timeouts || {};
function createTimeout(name, milliseconds, callback) {
timeouts.name = setTimeout(callback, milliseconds);
}
function removeTimeout(name) {
if (typeof(timeouts.name) !== undefined) {
clearTimeout(timeouts.name);
timeouts.name = undefined;
}
}
createTimeout('foo', 5000, function() {
alert('timeout')
});
</script>
i have also posted an example on jsFiddle http://jsfiddle.net/AGpzs/
I'm not sure what exactly you are doing, because as far as I can see you didn't post all the code, but this looks better for me:
function loadThumb(thumb) {
return setTimeout(function() {
loadThumb(next);
}, delay);
}
and then:
Load thumb 3

how to do a jQuery timeout

using jQuery... how do I run a function and then run a second function every 2 minutes after.
eg:
function 1: runs once
function 2: runs every 2 minutes after function 1 has finished
Any help will be much appreciated.
C
function f2(){}
function f1(){
... some code ...
setInterval(f2, 2000*60);
}
//From somewhere in your code, call f1
f1();
setInterval also returns a handle which can be used to cancel further calling of that function.
jQuery's delay() function is not a replacement for javascript's setInterval or setTimeout. To run a function #1 once on page load and then function #2 every 2 minutes after:
function funcOne() {
// some javascript
setInterval('funcTwo()', 1000*60*2);
};
function funcTwo() {
// some other javascript
};
$(document).ready(function() {
funcOne();
});
Remember, you are using JQuery because it makes javascript more simple. JQuery is a javascript library, not a language, wich means you can perfectly use javascript functions on it.
For your problem, you only need to call, with the setTimeout, your second function, and put inside this function another setTimeout(ms);
Like this:
function f1(/*...*/){}
var t = setTimeout("f2()",2 * 60 * 1000);
And at the end of your f2() function you should include another setTimeout, in order to call that function every 2 minutes.
function f2(/*...*/){
//...
t = setTimeout("f2()",2 * 60 * 1000);
}
To cancel this callings to f2() is just as simple: clearTimeout(t);
I would rather use setTimeout(). It is supposed to be less demanding on the browser, more processor efficient.
Here's what your functions should look like:
function f2(){
t = setTimeout(f2, 2000 * 60);
// code for f2
}
function f1(){
// code for f1
setTimeout(f2, 2000 * 60);
}
Then wherever it is you want the whole thing to start, call the first function:
var t;
f1();
You can stop the loop anytime:
clearTimeout(t);
Be sure to trigger setTimeout at the beginning of f2, so that it fires exactly every 2 minutes. Any code before 'setTimeout', taking 'x' time to process would result in the next f2 call firing after 2min+x.
Heloo
if i get you right then this is a solution
function func1()
{}
function func2()
{}
window.onload = function()
{
func1();
var flag_first_call_is_after_2=0;
var interv = setInterval(
function()
{
if(flag_first_call_is_after_2==0)
{
flag_first_call_is_after_2=1;
}
else
{
func2();
}
}
,120000
);
}

Best way to put delay after calling javascript functions

I'm using jquery to call some javascript functions with a delay between them.
Also I'm using Jquery Wait
When I call below function,all functions are called recpectively,there are no delays between each other.
$(this)
.call(f1)
.wait(5000)
.call(f2)
.wait(5000)
.call(f3);
Here call function calls some function as I did
$.fn.call = function (f) {
if (f)
f();
return this;
};
What am i doing wrong ?
How can i achieve something like this ?
Thank you
If you want to call a function every 5 seconds use
setTimeout(function(){f1},5000);
setTimeout(function(){f2},10000);
setTimeout(function(){f2},15000);
if you want to call each function 5 seconds after the last one terminated use
setTimeout(function(){f1;setTimeout(function(){f2;setTimeout(function(){f3},5000);},5000);},5000);
You don't need wait() from that cookbook; delay() is built-in and appears to have the same functionality. But either function involves adding something to jQuery's internal queue of effects and then removing it after a timeout expires, i.e. it's not a sleep statement, so it's not going to wait around before returning.
If you want to use delay() or wait(), you should make call() enqueue the function with queue(). Just sketching, but something like:
$.fn.call = function(f) {
if (f) {
$(this).queue(function() {
f();
$(this).dequeue();
}
}
return this;
}
Then I'd expect your code to work the way you intend.
Here is a function that calls in sequence an array of function:
$.fn.callFn = function(fns, delay) {
var fn, that = this;
if(fns.length > 0){
fn = fns.shift()
fn && fn();
setTimeout(function(){
that.callFn(fns, delay);
}, delay);
}
return this;
};
And you would call it like that:
$(this).callFn([f1, f2, f3], 2000);
$('#box').slideUp(300).delay(800).fadeIn(400);
/* .delay = wait time = 800 (this means it will wait 800/1000 of a second/ "1000 = 1 second") */

Categories