javascript - How to use mouse event to do AJAX call only if user is idle for X seconds -


apologies if repost. have seen many examples. can't seem put needs. have "today" page displays groups. throughout day more , more groups appear. want able dynamically update these groups if user has page open , hasn't moved mouse x seconds. have chunk of code:

var timeout = null;     j$(document).on('mousemove', function() {         if (timeout !== null) {             cleartimeout(timeout);         }         timeout = settimeout(function() {             timeout = null;             //calls page check if there's new data display. if so, wipe existing data , update             j$.ajax({                   url: "/include/new_groups.php",                   cache: false,                   success: function(data){                       j$( ".group_container_main" ).append( data ).fadein('slow');                   }                 })                   .done(function( html ) {               });         }, 3000);     }); 

what doing if user hasn't moved mouse after 3 seconds, ajax call update group. semi works. if don't move mouse, update. won't update again unless mouse moved , idle again 3 seconds not user experience.

i'm trying find way continually update page every 3 seconds (for example) if user idle. if he's moving mouse, there no updating. please ask questions if i'm unclear! in advance.

should straigh forward, use interval , function call instead

jquery(function($) {     var timer;      $(window).on('mousemove', function() {         clearinterval(timer);         timer = setinterval(update, 3000);     }).trigger('mousemove');      function update() {         $.ajax({             url    : "/include/new_groups.php",         }).done(function (html) {             $(".group_container_main").append(html).fadein('slow')         });     } }); 

fiddle

edit:

to solve issue of stacking ajax requests if reason take more 3 seconds complete, can check state of previous ajax call before starting new one, if state pending it's still running.

jquery(function($) {     var timer, xhr;      $(window).on('mousemove', function() {         clearinterval(timer);         timer = setinterval(update, 1000);     }).trigger('mousemove');      function update() {         if ( ! (xhr && xhr.state && xhr.state == 'pending' ) ) {             xhr = $.ajax({                 url    : "/include/new_groups.php",             }).done(function (html) {                 $(".group_container_main").append(data).fadein('slow')             });         }     } }); 

Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -