2016-04-24 87 views
0

我试图在jquery mobile中创建一个函数,该函数在特定页面上每3秒自动刷新一次。在jquery mobile中每3秒执行一次函数

我曾尝试:

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

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

}); 

我怎样才能改变功能CONSOLE.LOG(“其3秒后”)3秒钟后,这是我怎样才能添加的时间只有interval.The函数应该当执行一个是在页面(#chat)

+0

'window.setInterval()'? – Redu

+0

http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript的副本? –

回答

2

可以使用setInterval方法,它将在(以毫秒为单位)所需的时间间隔执行指定的功能。

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

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

    setInterval(autoload(), 3000); 

}); 

要隐藏页面时停止执行,你可以存储间隔ID,并使用clearInterval方法。

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

您还可以使用setTimeout方法,类似于setInterval方法。

// 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); 
}); 
+0

感谢它的工作,但我如何停止页面隐藏功能,因为即使当我离开页面时功能仍然继续 –

+0

另一种做法是使用间隔ID。这将允许您管理多个间隔。请参阅http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript –

1
$(document).on('pageshow', '#chat',function(){ 
    function autoload(){ 
     console.log('its after 3 sec') 
    } 
    window.setInterval(autoload, 3 * 1000) 
}); 
+0

它可以在页面隐藏 –

+0

@GEOFFREYMWANGI上工作,你需要使用'var myInterval = window.setInterval(...)'跟踪计时器,然后你可以用'window.onblur = function永久停止它(){clearInterval(myInterval)}' – Plato