It is considered bad practise to pass setTimeout
a string. This is similar to using eval()
, which is evil in JavaScript.
function onload_animate(id_name, img_src1, img_src2, time_ms){
document.getElementById(id_name).src = img_src1;
setTimeout(function () {
onload_animate(id_name, img_src1, img_src2, time_ms);
}, time_ms);
document.getElementById(id_name).src = img_src2;
};
Will capture the variables so they are available within setTimeout
. Note that this function will currently loop forever; you need some form of exit (usually checking a conditional; e.g. has time_ms
expired yet?)
Your code should probably look something like this;
function onload_animate(id_name, img_src1, img_src2, time_ms) {
document.getElementById(id_name).src = img_src1;
setTimeout(function () {
onload_animate(id_name, img_src2, img_src1, time_ms);
}, time_ms);
};
See this snippet for a working example: http://www.jsfiddle.net/3vKnW/.
JavaScript does not wait for setTimeout
to complete. It is asynchronous. JavaScript will hit the setTimeout
line, schedule the function to be ran in time_ms
time, but will then go back and continue executing where it left off.