GEOFFREY MWANGI GEOFFREY MWANGI - 7 months ago 10
Javascript Question

Execute a function every 3 seconds in jquery mobile

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)

Answer

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);

});

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

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

    function autoload() {
        console.log('its after 3 sec')
        setTimeout(autoload(), 3000);
    }
});
Comments