简体   繁体   中英

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?

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM