views:

259

answers:

3

I want to execute a particular number of statements after some delay. For eg:

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}
function gotoDiv(index) {
    var ele = document.getElementById("Div" + index);
    var x = findPosX(ele);
    var y = findPosY(ele);
    setTimeout("window.scrollTo(x, y)", 5000);
}

Here I want to set the current scroll position to a prticular div. But it's giving me error: x is undefined. Let me tell u if I use the functions as below it works fine, so please don't tell me that ele is null and blah blah blah.

function gotoDiv(index) {
    var ele = document.getElementById("Div" + index);
    var x = findPosX(ele);
    var y = findPosY(ele);
    window.scrollTo(x, y);
}

Any help appreciated.

+4  A: 
Natrium
Do not pass JS code as string to setTimeout function. Please pass a regular javascript function.
SolutionYogi
Worked like a charm...Thanks buddy !!
Manish
Way to rip bdukes' answer after the fact.
Crescent Fresh
at least I admit my original answer was not the best one. bdukes is geting more votes so no worries.
Natrium
+1  A: 

Wrap the function in a closure and then put the timeout inside the closure.

Evernoob
already tried that but what if the function requires a paramter?? It's giving the current error bcoz of the same reason..!!
Manish
+13  A: 

You can give setTimeout a function, rather than a string, which will let you access those variables:

setTimeout(function() { window.scrollTo(x, y); }, 5000);
bdukes
Great...this is working too...!!! Thanks ...
Manish