AlpaxJ1
AlpaxJ1

Reputation: 125

Javascript Timers not consistent

I know there has been many topics on Javascript Timers however, my timers are in effect "Doubling" every time my mouse hovers over a div to call a command, they are not consistent.The divs below show the onmouseover event which calls the functions.

<div id="Team_Container2"><div id="Image1" onmouseover="area_hover1(this);area_hover2(this)"></div>
<div id="Team_Container2"><div id="Image2" onmouseover="area_hover1(this);area_hover2(this)"></div>



function area_hover1(obj) {
    var interval;
    clearInterval(interval);
    href = $(obj).attr('href');
    url = href.split('#');
    url1 = url[1];
    interval = setInterval(function() {setAreaOver(document.getElementById(url1), 'Seating_Plan_Image_canvas', '0,0,0', '0,0,0', '0.33', 0, 0, 0);}, 1000);
            return;
}

function area_hover2(obj) {
        var interval;
        href = $(obj).attr('href');
        url = href.split('#');
        url1 = url[1];
        clearInterval(interval);
        interval = setInterval(function() {setAreaOver(document.getElementById(url1), 'Seating_Plan_Image_canvas', '0,0,0', '0,0,0', '0.0', 0, 0, 0);}, 2000);
        return;
}

How could i adjust the timer or merge the two functions into one and perform one "setInterval" after the other one.

I need the area_hover2 set Interval to come like 500 milliseconds after the first Area_hover1 set interval if that makes sense.

Any help would be most appreciated!

Thanks Aj

Upvotes: 0

Views: 433

Answers (1)

MidnightLightning
MidnightLightning

Reputation: 6928

Every time you hover over your image, you kick off a new setInterval, since your clearInterval() command isn't really doing anything. You defined the variable holding the setInterval() pointer inside the hover function, so as soon as it exits, that variable is gone. What you need is:

var interval; // Defined in global scope
function area_hover1(obj) {
   clearInterval(interval); // Abort any existing hover interval
   // Set up variables
   interval = setInterval(function() { /* doStuff */ }, 1000);
}

You may also need to capture the onMouseOut event to stop the interval as well, since right now it will keep running even after the mouse is no longer hovering over the element.

Upvotes: 1

Related Questions