Larger delay on first run - javascript

Im having problems delaying the first run of a function. I've created a very simple slideshow but because of that I'm having problems delaying the first run.
I want the first run to wait 10 seconds and then keep the 4 second delay between the rest of the images.
This is my code:
function slideshow() {
$("#slideshow .slide:hidden:first").fadeIn(1000).delay(4000).fadeOut(1000, function() {
$(this).appendTo($(this).parent());
slideshow();
});
}
$(document).ready( function () {
$("#slideshow .slide").hide();
slideshow();
});
I've tried a few different things but none successful.
I don't think jsfiddle is needed on this issue but if you want it just comment and i'll set it up!
Thanks in advance!

You're looking for Javascript's built-in setTimeout function, it creates a timer and executes the passed code after the timer finishes. In your $(document).ready() you can try this:
setTimeout( slideshow, 10000);
This will delay the execution of your slideshow function for 10 seconds. Documentation here

Use a timeout on the first call to your slideshow function. setTimeout accepts the second parameter as the amount of milliseconds to wait before executing the code in the argument. 10,000 milliseconds is 10 seconds.
$(document).ready( function () {
$("#slideshow .slide").hide();
setTimeout(function(){slideshow();},10000);
});

Related

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)

News ticker: Recursion Error

I was trying to implement a simple news ticker for a website I am creating.
Being new to JS and JQuery, I got the code off a website. The code works perfectly fine, but a too much recursion (firefox) error occurs when I shift the function call.
Original function:
$(document).ready(function(){
var tick=function()
{
window.setTimeout(function()
{
$('#ticker li:first').animate({marginTop:"-30px"},700,function()
{
$(this).detach().appendTo('#ticker').removeAttr('style');
});
tick();//Old position for function call- works fine
},4000);
};
tick();
});
The above code works, but when I shift the recursive call to outside the setTimeout function, the a recursion error. Slightly altered code:
$(document).ready(function(){
var tick=function()
{
window.setTimeout(function()
{
$('#ticker li:first').animate({marginTop:"-30px"},700,function()
{
$(this).detach().appendTo('#ticker').removeAttr('style');
});
},4000);
tick();//New position for function call-leads to unresponsive page
};
tick();
});
My question is this : shouldn't both the above codes works in the exact same manner? What changes when the location changes?
The purpose of the setTimeout function is to set another function to run after a specified amount of time. However, the timeout runs without blocking other code from executing -- the setTimeout function only sets the timeout, it executes immediately rather than waiting for the function passed to it to actually run. When you have the tick() call inside the setTimeout function call with a timeout of 4000 ms, you get the effect of rerunning the tick() every four seconds. However, once you move it outside the setTimeout call, it's rerunning instantly and infinitely as soon as you call it the first time.
In the first case, tick() doesn't call itself until the timer stops because the call to itself resides within the setTimeout() function. In the second case, tick() is instantly calling itself, with no timeout in between. This will call itself infinite times and if the browser didn't give you the recursion error and allowed it to continue, it would lock up or crash the browser eventually.
To show that, the second case can be simplified to:
var tick=function(){
tick();
};
tick();
You are simply moving the tick() inside the setTimeout. Here's your new code. If you don't do this, tick() will be called immediately.
$(document).ready(function(){
var tick=function()
{
window.setTimeout(function()
{
$('#ticker li:first').animate({marginTop:"-30px"},700,function()
{
$(this).detach().appendTo('#ticker').removeAttr('style');
});
tick();//New position for function call-leads to unresponsive page
},4000);
};
tick();
});

Function in function cycle

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();

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