开发者

Rails Javascript Database Doubt

开发者 https://www.devze.com 2023-03-17 16:01 出处:网络
I am trying to display a set of images at certain time intervals in my rails application. Now i am using javascript for this and taking the timings from the user for the time between each slide to be

I am trying to display a set of images at certain time intervals in my rails application. Now i am using javascript for this and taking the timings from the user for the time between each slide to be displayed. Now for that i am using the setTimeout function of javascript in which i am trying to fetch the time from the database,ie, my table named slides.

This is my code snippet for preloading images

var preloaded = new Array();


for (var x = 0; x < 10; x++)
{
    preloaded[x]     = new Image();
    preloaded[x].src = "/images/pausch/img"+x+".gif";
}

This is my snippet of the image changing function

    function slideit(){
//if browser does not support the ima开发者_运维技巧ge object, exit.
if (!document.images)
return;
document.images.slide.src=eval("preloaded["+step+"].src");
if (step<10)
step++;
else
step=0 ;
<% @slides.each do |slide| %>
setTimeout("slideit()",'<%= slide.time.to_i %>')

    <% end %>
}

However the images are changing are some random times and not according to the time stored. Can anyone suggest whats wrong?


Try removing the setTimeout() call from inside the function, and put a call to (say) setInterval(slideit,1000) somewhere outside the function:

    ....
    document.images.slide.src = preloaded[step].src; 

    if (step<10) step++;
    else step=0;
}
setInterval(slideit,1000);

This will cause slideit() to be called every 1000 miliseconds, rather than assigning multiple timeouts each time the function is called.

Note I also removed the eval() call and some extra quotes from your preloaded[step].src line - It won't affect the timeout stuff, but you shouldn't need eval here because the contents of the array is just a string (and for security reasons it's generally good to avoid using eval() if you can).

Edit: Just saw that you want different timeouts for each image. I would do this with a single call to setTimeout():

    ....
    document.images.slide.src = preloaded[step].src; 

    setTimeout(slideit,timeouts[step]);

    if (step<10) step++;
    else step=0;
}

For this solution, you'll want to initialise an array called timeouts where each entry timeouts[x] contains the number of miliseconds to display image x.

0

精彩评论

暂无评论...
验证码 换一张
取 消