简体   繁体   中英

I get “function not defined” using setInterval with jQuery. Why?

I am trying to update a users field by using jQuery.

My code is...

  jQuery(document).ready(function(){
  setInterval("imStillAlive()", 6000);
    function imStillAlive() {

      jQuery.post('/users/update_useractive',
     function(data){
    alert("updated");
     });//post
   }
    });

The above code when ran shows the error...

"imStillAlive" not defined

How to resolve this?

Few issues here...

  • "imStillAlive()" invokes an eval() type function internally. Don't do that.
  • You are posting inside a setInterval() . Wouldn't you rather know the post has finished before calling it again?
  • You are not doing any DOM manipulation, so don't wait for DOM ready.
  • imStillAlive() is a pretty bad name for a function.
  • Now this one is a little tangible, but if this is being used to determine if the user is still active on your site, isn't 6 seconds a little too frequent to update your database? Also, if someone leaves their browser open, won't this be chewing up resources unnecessarily? If many users leave their browser open, won't this be DOSing yourself? :P

This would seem better...

(function($) {

    (function update() {
        setTimeout(function() {
            $.post('/users/update_useractive',
               function(data){
                 alert("updated");
                 update();
            });
        }, 6000);
    })();

})(jQuery);

See it on JSFiddle.net

Try this solution, as mention by Alex, it not necessary to write it inside document.ready as you are not doing any DOM manipulation.

setInterval(function(){
    imStillAlive();
}, 6000);

function imStillAlive() {    
     jQuery.post('/users/update_useractive',
     function(data){
        alert("updated");
     });//post
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM