0

Am trying to create a function in jquery mobile that autorefreshes itself every 3 seconds when on a certain page.

I have tried:

 $(document).on('pageshow', '#chat',function(){

function autoload(){
   console.log('its after 3 sec')
     } 
autoload();

 });

How can i change the function to console.log('its after 3 sec') after 3 seconds that is how can i add the time interval.The function should only execute when one is on the page(#chat)

Geoff
  • 6,277
  • 23
  • 87
  • 197

2 Answers2

2

You can use the setInterval method, it will execute the specified function at the desired interval (in milliseconds).

$(document).on('pageshow', '#chat', function() {

    function autoload() {
        console.log('its after 3 sec')
    }

    setInterval(autoload(), 3000);

});

To stop execution when hiding the page, you could store the interval id and use the clearInterval method.

// store the interval id so we can clear it when the page is hidden
var intervalId;

$(document).on('pageshow', '#chat', function() {
    function autoload() {
        console.log('its after 3 sec')
    }
    intervalId = setInterval(autoload(), 3000);
});

$(document).on('pagehide', function() {
    clearInterval(intervalId);
});

You can also use the setTimeout method, similar to the setInterval method.

// store the timeout id so we can clear it when the page is hidden
var timeoutId;

$(document).on('pageshow', '#chat', function() {
    function autoload() {
        console.log('its after 3 sec')
        timeoutId = setTimeout(autoload(), 3000);
    }
    autoload();
});

$(document).on('pagehide', function() {
    clearTimeout(timeoutId);
});
matt.
  • 2,355
  • 5
  • 32
  • 43
  • Thanks it works but how can i stop the function on pagehide because the function continues even when am out of the page – Geoff Apr 24 '16 at 23:54
  • Another practice is to use the interval ID. This will allow you to manage multiple intervals. See http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript – Gjermund Dahl Apr 25 '16 at 08:44
1
$(document).on('pageshow', '#chat',function(){
    function autoload(){
        console.log('its after 3 sec')
    } 
    window.setInterval(autoload, 3 * 1000)
});
blex
  • 24,941
  • 5
  • 39
  • 72
Plato
  • 10,812
  • 2
  • 41
  • 61
  • It works what about stopping the function on pagehide – Geoff Apr 25 '16 at 00:02
  • @GEOFFREYMWANGI you will need to keep track of the timer with `var myInterval = window.setInterval(...)` and then you could permanently stop it with `window.onblur = function(){ clearInterval(myInterval) }` – Plato Apr 28 '16 at 20:41