Why is the JS Method setTimeout working Ok in 1 page and not other!

Hello,

We are using the JS Method setTimeout to fade-out a DIV after designated number of Seconds.
This is working fine here:

where as you can see the Pop Up window is called to fade away after 5 Seconds via setTimeout. And it does that exactly.

Whereas here:

the Pop Up window is fading away via setTimeout right after the page is loaded rather than WAIT 10 seconds before doing so!

here are related JS for this:

setTimeout(fade_div(‘two_mill_anon’), 10000);

function fade_div (id) {

document.getElementById(id).style.opacity = 0;

}

What is the problem?

Thanks.

The problem is that you’re calling fade_div directly, and passing the result – which is undefined – into the setTimeout function, which will simply do nothing. It becomes more obvious when you write it out:

var result = fade_div('two_mill_anon')  // undefined
setTimeout(result, 10000)

The solution is to return a new function that will get passed to setTimeout(), and remembers the id parameter by creating a closure:

function fade_div (id) {
  return function () {
    document.getElementById(id).style.opacity = 0
  }
}

setTimeout(fade_div('two_mill_anon'), 10000);

m3g, OK. Thanks.
FYI, we solved the problem by calling it this way:

fade_t = setTimeout(function(){ fade_div(‘two_mill_anon’) }, 7000);

rather than what was working on other page, which was:

setTimeout(fade_div(‘two_mill_anon’), 10000);

But your solution is interesting too and we shall study it.

Thanks
Dean @ Anoox.com

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.