views:

340

answers:

1

Hi,

If I want to use the mouse to scroll the window when it gets close to one of the edges how can I approach this?

So far I have it working fine, it checks the position whenever it moves to see if it is close enough to the edge to scroll.

However, it only checks the position whenever the mouse moves, so if you moved close the edge, it would scroll once, and it wouldn't check again to see if you're still close enough to scroll again.

How can I do this? A loop doesn't work, because it just freezes the browser by continually checking without breaking in between checks. I also tried doing this...

function startScrolling() {
    //If we're close to an edge start scrolling in that direction
    //Else stopScrolling = true;

    if(!stopScrolling) {
        setTimeout(startScrolling(), "1000");
    }
}

This function gets the position of the mouse from global variabels set by the on mouse move event, so techinally every time it executes it should have new mouse positions. But it doesn't even seem to wait before calling startScrolling() again... Any ideas?

Thanks, Matt

A: 

The problem with the code you posted is that you're executing startScrolling instead of passing it to setTimeout - i.e. you're calling startScrolling() and passing its result as the first parameter of setTimeout. Since its return value is null, nothing gets called after 1 second and that's why it seems to be ignoring it.

You want to do this instead:

setTimeout(startScrolling, "1000");

or:

setTimeout(function (){ startScrolling(); }, "1000");

The former is preferrable as it's shorter and more understandable, although in many cases you'll need the second one if you need to pass additional parameters to startScrolling.

Seb