I'm really struggling with this one - sure I'm missing something simple.
Here's the code :-
function webcamupdate(webcamurl) {
alert("I am a function to update the webcam with the url "+webcamurl);
}
function countdown(callback) {
alert(callback);
setTimeout("callback()", 10000);
}
var theurl = "THIS IS THE URL";
countdown(function(){ webcamupdate(theurl); });
As you can see, I'm trying to contsruct a countdown function (there is more code, however I have just posted the basics) which will run a function (in this case updating a webcam) after 10 seconds.
All works OK if the function has no arguments, however the alert(callback) in the coundown function returns the following :-
function(){ webcamupdate(theurl); }
This of course crashes the script when the webcamupdate function runs as "webcamurl" is not defined.
What alert(callback) actually needs to say is :-
function(){ webcamupdate("THIS IS THE URL"); }
i.e. it evaluates the argument "theurl" BEFORE passing it with the function.
Any ideas would be much appreciated
EDIT
I think I've perhaps misled you my using the alert rather than a function (I was just trying to keep it simple!)
Here's the original code (still cut down, but gives you a better idea).
function webcamupdate(url) {
document.getElementById("cruisecam").src=url+"&rand="+Math.random();
countdown(30,"Webcam",function(){ webcamupdate(url); });
}
function countdown(currentcount,displayelement,callback) {
var displaytext;
if (currentcount == 0 ) displaytext = displayelement+" is refreshing now";
else displaytext = displayelement+" updating in "+currentcount+" seconds";
if (trackingcountdown.hasChildNodes()) clearelement("trackingcountdown");
trackingcountdown.appendChild(document.createTextNode(displaytext));
if (currentcount == 0) {
countdown(currentcount,displayelement,callback)
}
else {
currentcount--;
var countdownparameters=currentcount+',"'+displayelement+'",'+callback;
setTimeout("countdown("+countdownparameters+")", 1000);
}
}
//The function is called on window loading with
//countdown(30,"Webcam",function(){ webcamupdate(url); });
//clearelement is another function (not listed) that clears the node.
Basically, it's the countdown function that matters - it takes 3 arguments - the countdown time in seconds, the DOM element to display the countdown, and the function to run on timeout.
If the 3rd argument (the function) doesn't have any arguments of its own - e.g. webcam() - it works fine, however when we trying adding webcam("webcampic.jpg") it doesn't work due to the function trying to run webcam(url) rather than webcam("webcampic.jpg").
Obviously the easiest solution is just to make the url a global variable, but this is not good practice and would stop me using the countdown code on other pages through a js file. help!