Function in function cycle - javascript

i need to load PHP file with random image to <div> every 2 seconds with fade effect so i use javascript and jQuery. I write function to hide div, load file in, than show it and wait 2 seconds, then it should call function again, but it happend just once then it stop.
Here is the function:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'}).delay(2000, function(){
random();
});
random();

Do this:
(function random(){
var timer;
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php", function(){
$(this).animate({opacity: '1'});
timer = setTimeout(random, 2000);
});
})();
Here we create self-invoking function and call it inside setTimeout so that it gets called again and again AFTER your image loading and animation part is complete. You would need to call clearTimeout(timer) to stop running setTimeout once all your images are loaded.

try adding setTimeout(random, 2000); after the load request is completed:
function random(){
var rndImg = $("#randomImage1");
rndImg.fadeOut().load("../images/randomImage.php",function(){
rndImg.fadeIn();
setTimeout(random, 2000);
});
};
random()

The problem you have is that you're trying to use .delay() as a replacement for the native setTimeout(), which isn't what it's intended to do. The .delay() function is designed to add a pause between jQuery animation effects, not to delay the execution of another function, and doesn't accept a callback function. See the jQuery documentation for the .delay() function.
As has already been covered in previous answers, you can use the native setInterval() function to implement the delay you're after:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'});
setInterval(random, 2000);
}
random();
Note that this will animate the #randomImage1 element back to full opacity, and set the interval to call the function again, even if the AJAX call from .load() didn't return a success response. If that's not what you want, you can instead move that code into an anonymous function passed as the success callback on .load(), like so:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php",
function() {
$("#randomImage1").animate({opacity: '1.0'});
setInterval(random, 2000)
});
}
random();

Related

Set delay on click event

I want to load this script after loading the page so I want to set a delay for this code to work -
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
If by "delay" you mean a timer and a function which is called after the timer finishes you might want to use setTimeout() function. argument 1 is the function to be called and argument 2 is the countdown time in milliseonds eg:
setTimeout(exec, 2000);
function exec() {
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
}
or if you mean execute the script after page has loaded try this
document.onload = function() {
document.getElementsByClassName("pdp-button_theme_bluedaraz")[0].click();
}

Weird behavior with SetTimeout

I'm trying to refresh a div with JavaScript every 20 seconds. This is my code:
$(document).ready(function(){
refreshTable();
updateTable();
});
function updateTable(){
setTimeout( refreshTable, 20000);
updateTable();
}
function refreshTable(){
$('#table_list').load('table')
}
Once the page is ready, I can start my countdown. But this code is updating the table every 3 seconds. Can someone help me? What am I doing wrong?
P.s.: I saw that is a common issue here, but any of the questions that I saw were able to help me.
When the document is ready, you call updateTable.
After 20 seconds, it calls refreshTable but it immediately calls updateTable again. So it queues up another refreshTable and then hits updateTable again. This sticks it into an infinite loop … or at least into stack overflow.
You need to either:
Call updateTable from inside refreshTable instead of updateTable
Use setInterval in the ready handler instead of using setTimeout at all
You have infinite recursion:
function updateTable(){
setTimeout( refreshTable, 20000);
updateTable(); // Infinite recursion.
}
You should use setIinterval instead of making your setTimeout loop.
As other answers are pointing out, you have infinite recursion in your updateTable function. You could instead use setInterval, which periodically runs the specified refreshTable function:
$(document).ready(function(){
refreshTable();
setInterval(refreshTable, 2000)
});
function refreshTable(){
$('#table_list').load('table')
}
$(document).ready(function(){
window.setInterval( function(){
$('#table_list').load('table');
}, 20000);
});
This might help you out, at least i hope so :D
I would recommend you to use the "complete" callback of the jQuery method ".load()"
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#table_list').load('table', function(){
setTimeout( refreshTable, 20000);
});
}
Thus, setTimeout will be executed after query processing and HTML insertion has been performed. Please notice that we don't need the "updateTable" auxiliary function anymore as we now call the "refreshTable" function recursively.

Trying to make a table row that deletes itself

I'm trying to make the top row of a table delete itself, every 5 seconds, using javascript. My javascript looks like this:
setTimeout(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
which gets it to delete the top row after 5 seconds. Is there a way to reset the setTimeout to begin counting down again?
In this case it looks like you are looking for the functionality of setInterval:
var myTimer = setInterval(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
If you would still like to use setTimeout you would want to call another setTimeout inside your function(){ ... }); that does the same thing. Basically have a function that keeps calling itself with a setTimeout like so:
(function loop() {
document.getElementById("myTable").deleteRow(0);
setTimeout(loop, 5000);
})();
Put it inside of a function and call it again.
function deleteRows(){
var t = setTimeout(function(){
document.getElementById("myTable").deleteRow(0);
clearTimeout(t);
deleteRows();
}, 5000);
};
You need to use setInterval instead of setTimeout .
Check the difference between them here: JavaScript Timing Events
setTimeout(function, milliseconds):
Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds)
Same as setTimeout(), but repeats the execution of the function continuously.
Therefor, you can rewrite your code as following:
var timer = setInterval(function(){
document.getElementById("myTable").deleteRow(0);
}, 5000);
Then if you want to stop the execution of that timer function, you can use:
window.clearInterval(timer);
I would use setInterval() instead. Inside your callback function check for number of rows and if the row exists then delete it, if it doesn't remove time interval.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval
JS Fiddle example: https://jsfiddle.net/n2yg4fv2/ (I used 1 second delay to make it faster)

Calling JavaScript Function that has SetTimeout Assigned to It

I'm not 100% sure how setTimeout works in JavaScript. Say I have something like this:
$(document).ready(function() {
testTimeout();
});
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
}
This would display a popup window every 5 after the page is ready. What would happen if then I called testTimeout from a button click?
$("#button").click(function() {
testTimeout();
});
Would the button click call testTimeout and add another timeout every 5 seconds? Or, would the button click reset the timeout from when the button was pressed? The reason I am asking is because I would like to design something like this where I can pass a parameter to my timeout function. When the web page starts up, I have a default parameter. However, if I press a button, I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating. How can I achieve this? Any help and understanding would be greatly appreciated.
This would display a popup window every 5 after the page is ready.
No it wouldn't, it would show an alert repeatedly with no delay and/or cause a "too much recursion" error, because setTimeout(testTimeout(), 5000) calls testTimeout and passes its return value into setTimeout, just like foo(bar()) calls bar and passes its return value into foo.
If you remove the ():
function testTimeout() {
alert("testing timeout");
setTimeout(testTimeout, 5000);
// here --------------^
}
Then it would do that.
What would happen if then I called testTimeout from a button click?
You'd end up with the function being called twice as often (more than once every 5 seconds), because every time you call it, it reschedules itself. A third time would make it more frequently still (three times/second), and so on.
If you want to avoid that, one option is to remember the timer handle and cancel any outstanding timed callback if you call the function before then:
var handle = 0;
function testTimeout() {
clearTimeout(handle); // Clears the timed call if we're being called beforehand
alert("testing timeout");
handle = setTimeout(testTimeout, 5000);
}
(I initialized handle with 0 because calling clearTimeout with a 0 is a no-op.)
Have you tried to asign variable to your setinterval;
var foo = setTimeout(testTimeout(), 5000);
and then when right event comes just destroy that variable.
clearInterval(foo);
And now you can asign it again...
In your case it would simply repeat endlessly, because you're executing the function instead of passing the reference. You should do it like this:
function testTimeout() {
alert("testing timeout)";
setTimeout(testTimeout, 5000);
}
Note the missing braces after testTimeout. This tells setTimeout to execute that function, instead of the result of that function, which is how your original code behaved.
" I would like my timeout function to be called right away and every 5 seconds after with my new parameter. But, I don't want the timeout function with the old parameter to continue repeating "
In order to achieve what you're trying to do you should remove the timeout:
var timeoutId;
function testTimeout() {
alert("testing timeout)";
clearTimeout(timeoutId );
timeoutId = setTimeout(testTimeout, 5000);
}
Notes:
You can stop the previous timeoutI from firing by catching the id returned from the setTimeout method and passing that to the clearTimeout method

Javascript timing problem

I wont to run a block of code in a certain amount of time and then when done, carry on with another block of code.
Using the setTimeout() is probably what you want. For example...
<script type="text/javascript">
function YourFunction()
{
alert('Hello Stackoverflow');
}
window.setTimeout(YourFunction, 1000);
</script>
Hope it helps
This is how you would do it, using the setTimeout function, which takes code to call as the first argument and how much time it should wait before calling it (in milliseconds) as the second argument:
function callWhenDone() {
// code to call when timeout finishes
}
setTimeout(function() {
// initial code to run
callWhenDone();
}, 5000); // 5000 = run in 5 seconds
Because of the nature of Javascript you have to encapsulate the code you want to run after the timeout is finished in its own function, otherwise it would be run before the timeout is finished. This is, in essense, a callback, and it is a big part of the event-based nature of Javascript.
You'll want to use the setTimeout() function.
setTimeout - executes code after a time interval
clearTimeout - cancels the setTimeout()
More details here.
Use setTimeout.
setTimeout(function() {
// code here
// you can use it recursively
// setTimeout(...);
},
1000 // 1000 miliseconds (= 1 second)
);
and setInterval is like setTimeout, except it repeats a code repeatedly.
<script type="text/javascript">
var timer = setInterval("firstFunction()","1000"); //every second call firstFunction()
var i = 0;
function firstFunction()
{
//first code
i++;
if(i == 3)
{
clearInterval(timer);
secondFunction();
}
}
function secondFunction()
{
//second code
alert("done!");
}
</script>

Categories

Resources