jquery - Timed AJAX request, reload if content is different -


i using following script check if content of currentshow.php , #current-show (on existing page) different. if different want replace #current-show currentshow.php:

jquery(document).ready(function() {  var auto_refresh = setinterval(     function (){         function getcurrentshow(){          var result = null;          jquery.ajax({             url: '/currentshow.php',             type: 'get',             datatype: 'html',             async: false,             success: function(data) {                 result = data;             }           });          return result;         }          gcs = getcurrentshow();         cs = jquery('#current-show').html();         if (gcs != cs){             jquery('#current-show').load('/currentshow.php');         };     }, 1000); )}; 

i console.log(gcs) , console.log(cs) , both return same thing in js console. however, content reloads every second anyway.

any idea doing wrong?

you code has drawbacks.

  1. you making sync request bad practice , deprecated in main ui thread.
  2. you making requests twice.
  3. you using setinterval if network lags few seconds?
  4. you accessing dom check if data changed.

consider following fiddle. http://jsfiddle.net/pxe2v/

var prev; //store previous data here function update() {     $.get('/currentshow.php').done(function(data) {         if(data !== prev) { //if data changed perform dom manip.             $('#current-show').html(prev = data);             }     }).always(function() { //launch next request when prev done.         settimeout(update, 1000);         });             }  update(); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -