Howard Jess <howard..@dhitechnologies.dot.com> writes:
If you really want to do this by passing a string rather than a
function reference to setTimeout, try:
function Hide(divId,timeout) {
hider = new Function("var elm=null;" +
"if (document.getElementById) " +
"elm=document.getElementById('"+id+"');" +
"if (elm && elm.style) elm.style.display='none';");
setTimeout("hider()",timeout);
}
No need to use the Function constructor here. A local function
declaration will do just as well, and should work everywhere
the outer declaration does.
function hide(divId, timeout) {
function localHider() {
var elem = nukk;
if (document.getElementById) {
elm = document.getElementById(divId);
} // else fallback to document.all or even document.layers
if (elm) {
var estyle = elm.style || elm;
estyle.display="none";
}
}
hider = localHider;
setTimeout("hider();", timeout);
}
Multiple invocations will redefine the "hider" function, however,
so it's far safer to pass a function reference.
Absolutely.
If that's simply not possible, do your best to ensure a unique name
for each time you run "Hide".
You could build your own abstraction over setTimeout that works either
way:
---
timer = new Object();
timer.nextCtr = 0;
timer.funcs = new Array();
timer.setTimeout = function _setTimeout(func, time) {
var id = this.nextCtr++;
if (typeof func != "function") { // not a function, convert to string
timer.funcs[id] = new Array(setTimeout("delete timer.funcs["+id+"];"+func, time));
return id;
}
// a function:
function wrapper() {
delete timer.funcs[id];
func();
}
wrapper.toString = function () {
return "timer.funcs["+id+"][1]()";
};
timer.funcs[id] = new Array(setTimeout(wrapper, time), wrapper);
return id;
};
timer.clearTimeout = function _clearTimeout(id) {
var pair = timer.funcs[id];
if (pair) {
delete timer.funcs[id];
clearTimeout(pair[0]);
}
}
---
You can then use it as, e.g.:
timer.setTimeout(function(){alert("X");},2000);
var id = timer.setTimeout(function(){alert("Y");},1500);
timer.setTimeout(function(){alert("Z");},1000);
timer.clearTimeout(id);
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'