Marcus
Marcus

Reputation: 1232

Function setTimeout throws error

I've a problem with the setTimeout function. This is the code:

1   var urlArray = ["pic1.gif"; "pic2.gif"]

2   function changeBackground(elementId, backgroundImage){
3       document.getElementById(elementId).style.background="url("+backgroundImage+")";
4   }

5   function mouseover_1(elementId){
6           changeBackground(elementId,urlArray[0]);
7           setTimeout("changeBackground(elementId,urlArray[1])",300);
8   }

And in the body:

<area shape="rect" coords="0,0,95,91" onMouseOver="mouseover_1('navigator_1')">

Now, line 6 in the Javascript code works like a charm (the picture changes!), but line 7 doesn't work (no picture change). This is the error from debugging in Firefox:

elementId is not defined  line: 7

But since line 6 works, I really don't know what the problem could be. Do you have any suggestions?

Upvotes: 0

Views: 167

Answers (3)

jdurango
jdurango

Reputation: 543

You can try this form to pass parameters to setTimeout function:

setTimeout(changeBackground, 300, elementId, urlArray[1]);

and here you can see other forms to do the same:

Passing parameters to a function called with setTimeout

Upvotes: 4

Marcus
Marcus

Reputation: 1232

After reading this: http://www.makemineatriple.com/2007/10/passing-parameters-to-a-function-called-with-settimeout

...I learned that a "parameter = null" is needed and finally implemented a closure:

setTimeout(function(){changeBackground(elementId,urlArray[1]);
    parameter = null},300);

But the function setTimeout() must always be wrapped into a setInterval()-thread, otherwise it won't run smooth.

Upvotes: 0

James M
James M

Reputation: 16718

If you pass a string to setTimeout, the string is not evaluated in the context of your function (so elementId does not exist).

You should use a closure instead:

setTimeout(function()
{
    changeBackground(elementId, urlArray[1]);

}, 300);

Upvotes: 5

Related Questions