Weird behavior with SetTimeout - javascript

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.

Related

Recursive setTimeout calls mysteriously stop running

I want to call a function in JavaScript continuously, for example each 5 seconds until a cancel event.
I tried to use setTimeout and call it in my function
function init()
{ setTimeout(init, 5000);
// do sthg
}
my problem is that the calls stops after like 2 min and my program is a little bit longer like 5 min.
How can i keep calling my function as long as i want to.
thanks in advance
The only conceivable explanations of the behavior you describe are that:
As another poster mentioned, init is somehow getting overwritten in the course of executing itself, in the // do sthg portion of your code
The page is being reloaded.
The //do sthg code is going into some kind of error state which makes it looks as if it not executing.
To guarantee that init is not modified, try passing the // do sthg part as a function which we will call callback:
function startLoop(callback, ms) {
(function loop() {
if (cancel) return;
setTimeout(loop, ms);
callback();
}());
}
Other posters have suggested using setInterval. That's fine, but there's
nothing fundamentally wrong with setting up repeating actions using setTimeout with the function itself issuing the next setTimeout as you are doing. it's a common, well-accepted alternative to setting up repeating actions. Among other advantages, it permits the subsequent timeouts to be tuned in terms of their behavior, especially the timeout interval, if that's an issue. If the code were to be rewritten using requestAnimationFrame, as it probably should be, then there is no alternative but to issue the next request within the callback, because requestAnimationFrame has no setInterval analog.
That function is called setInterval.
var interval = setInterval(init, 5000);
// to cancel
clearInterval(interval);

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

Switching between setTimeout function in javascript

I have setTimout function like this
setTimeout(function(){
//doing something here
},1000);
another setTimeout func like this right after the above func
window.setTimeout(function(){
//code here
},10000);
What I need to achieve is I need to read some files in first setTimeout function and do some processing,once the timeout over control should go to second timeout function,do some stuff there.Then get back to the first timeout function,do some processing there,when timeout over callback the second fun and so on..Like that I need to do for n number of files.
But whats happening is if I give for loop inside the first setTimeout fun,it process all the files and control is passed to second timeout fun with the last processed file.But what i want is to do that for each file??
How can i achieve this?Am newbie in Javascript. Any help?
function timeout1() {
console.log("This is timeout 1");
window.setTimeout(timeout2, 500);
}
function timeout2() {
console.log("This is timeout 2");
window.setTimeout(timeout1, 500);
}
// Kick it off.
timeout1();
Instead of using two Time outs why didn't you use wait like below?
setInterval(function(){alert("Hello")},3000);
Check this for a detailed explanation.
Hope this helps.
Please leave a feed back.

Larger delay on first run

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

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

Categories

Resources