SetTimeout fails
My setTimeout function doesn't want to work. I am not getting any warnings, so I guess I did something incredibly stupid.
var timeout = 1000;
for(k=0;k<pages.length;k++)
{
randomnumber=Math.floor(Math.random()*pages[k].length);
setTimeout(function() {
$.ajax({
type: 'GET',
url: pages[k][randomnumber],
success: function(data) {
alert(data);
if(data.indexOf('VIDEO_LENGTH') > 0)
{
timeouttext = data.substr(data.indexOf('VIDEO_LENGTH')+12);
timeouttext = timeouttext.substr(timeouttext.indexOf('.'));
timeout = parseInt(timeouttext);
alert(timeout);
}
else
timeout = 1000;
$('#loader').hide('fast','fade');
$('#information').html(data);
$('#information').show('fast','fade');
}
})
},timeout);
alert("PAGE " + k + " RandomNumber " + randomnumber + " : " + pages[k][randomnumber]);
if(k==3) {
k = 0;
}
}
Can anyone help me.
source to share
EDIT: ok follows the error:
var k when you call the page url is not what you expected. So try:
{
randomnumber=Math.floor(Math.random()*pages[k].length);
var selectedIndex = k; // store current k
setTimeout(function() {
$.ajax({
type: 'GET',
url: pages[selectedIndex][randomnumber], // use stored k
...
source to share
Your setTimeout is correct. To additionally check for errors:
-
check if your request is being sent.
-
add
error: function(){}
orcomplete:function(){}
block that logs the status of the request to see if your server side is breaking your code.
edit: (I suggest you don't use shorthand if
, it's very error prone.
source to share
Try the ( Updated ) fiddle here .
var funfacts= ['URL1','URL2','URL3'];
var multimedia= ['URL4','URL5'];
var employees = ['URL6','URL7','URL8','URL9','URL10'];
var information = ['URL11','URL12','URL13'];
var pages = [funfacts, multimedia, employees, information];
var timeout=1000;
var t=0;
for(i=0;i<pages.length;i++)
{
(function(value){
for(j=0;j<pages[value].length;j++)
{
t++;
(function(iv, ij){
var tmo = timeout*t;
setTimeout(function(){
callAjax(iv, ij);
}, tmo);
})(value, j);
}
})(i);
}
function callAjax(i, j)
{
$.ajax({
type: 'GET',
url: pages[i][j],
success: function(data) {
if(data.indexOf('VIDEO_LENGTH') > 0) // indexOf should be checked if(var.indexOf('sometext')!=-1)
{
// your code
}
else
{
// your code
}
}
});
}
If everything else is okay, then it should work.
source to share