I get "function not defined" using setInterval with jQuery. Why?
I am trying to update a users field by using jQuery.
开发者_如何学CMy 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 aneval()
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
}
精彩评论