I get a "not defined function" using setInterval with jQuery. What for?

I am trying to update a user field using jQuery.

My code ...

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

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

The above code at startup shows an error ...

"imStillAlive" not defined

How to resolve this?

+3
source share
2 answers

Try this solution, as Alex mentions, there is no need to write it inside the document. As you do not do any manipulations with the DOM.

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

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

A few questions here ...

  • "imStillAlive()"calls a type function eval()inside. Do not do this.
  • You publish inside setInterval(). Didn't you know that the message ended before calling him again?
  • DOM, , DOM .
  • imStillAlive() - .
  • , , - , 6 ? , - , ? , DOSing ?: P

, ...

(function($) {

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

})(jQuery);

JSFiddle.net

+3

Source: https://habr.com/ru/post/1777381/


All Articles