0

I have a column in my web design, which is periodically refreshed by a JS function "refreshColumn()" and updated by AJAX.

setInterval('refreshColumn()',60000);

function refreshColumn() {
..make call with AJAX and load response to element...
document.getElementById('myColumn').innerHTML = xmlhttp.responseText;
}

This is okay, however, it's not very practical when my user is actually using that column and it refreshes on them!

Is it possible to modify what I have already, to incorporate an 'onmouseover' event that will stop the function from running the AJAX and refreshing the column, and 'onmouseout' allows the script to refresh again?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
TheCarver
  • 19,391
  • 25
  • 99
  • 149

1 Answers1

2

You would use a timeout instead of an interval, and just clear it on mouseover and reset it on mouseout.

Live Demo

var timeout = setTimeout(refreshColumn,60000);

function refreshColumn() {
    // ajax call ect. reset the timeout
    timeout = setTimeout(refreshColumn,60000); 
}

element.onmouseover = function(){
   clearTimeout(timeout);
}

element.onmouseout = function(){
   timeout = setTimeout(refreshColumn,60000); 
}
Loktar
  • 34,764
  • 7
  • 90
  • 104
  • I always thought setTimeout only performed once, after 60 seconds, not every 60 seconds. Will this run every 60 seconds? – TheCarver Oct 12 '11 at 14:15
  • @MartinG just edited my answer. You just reset the timeout at the end of the refresh column function and itll keep going forever. – Loktar Oct 12 '11 at 14:19
  • You could just clear the interval and the reset the interval? That's kinda what the interval function is for... to have something run at specific intervals. I wonder if there are benchmarks against using setTimeout like you have over setInterval? – Alex Oct 12 '11 at 14:23
  • 1
    http://stackoverflow.com/questions/729921/settimeout-or-setinterval - there we go, apparently not really – Alex Oct 12 '11 at 14:25
  • eh, I always use timeouts due to operations not queuing up if they end up taking longer than the timeout threshold you specify. Intervals will continue to que up, so if I set one for 300ms and the operation takes 500ms to complete, Im going to end up having a lot of operations qued up. – Loktar Oct 12 '11 at 14:26
  • Thanks to Alex for sharing that link. Well seeming as I have users with old browsers and also have users that use IE mobile, I think setTimeout is probably the one – TheCarver Oct 12 '11 at 15:35