PSport PSport - 3 months ago 14
jQuery Question

Reload current function after time withouth reload page

If possible, I'd like to reload a jQuery

prototype
/
function
after a delay without refresh all the page.

my.prototype.reloadMe = function () {
setTimeout(function(){
my.reloadMe();
},1000);
alert('ok');
};


I tried with a
setTimeout
in the function but it didn't work: it refreshs only one time.

Thanks for your suggestions or explanations.

Answer

In your code you define a prototype function, and then you try to call it as an object function. You should get an error like "my.reloadMe() is not a function".

my.prototype.reloadMe = function () {
    setTimeout(function(){
      my.reloadMe(); // "my" object does not contain "reloadMe" function 
    },1000);
    alert('ok');
};

If you want to access this function, you can either call this prototype function explicitly:

setTimeout(function(){
  my.prototype.reloadMe();
}, 1000);

or instantiate your object and call this function:

setTimeout(function(){
  new my().reloadMe();
}, 1000);

which both do not sound correct.

It looks like the best solution is to name your anonymous function:

my.prototype.reloadMe = function reload() {
    setTimeout(reload, 1000);
    alert('ok');
};);

Note 1: in your code you use setTimeOut, while it is setTimeout. JS is case-sensitive. Perhaps, it can be a source of the error.

Note 2: any of this code will make it run in an infinite loop. So, actually, you will get an alert every second. I hope that it is exactly what you are trying to achieve :)

Comments