2016-04-24 12 views
0

jquery mobileで関数を作成しようとしていますが、特定のページに3秒おきに自動再読み込みしています。 3秒後にjquery mobileで3秒ごとに関数を実行

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

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

}); 

にはどうすれば(「その3秒後に」)はconsole.logする機能を変更することができ、私はinterval.The機能のみをする時間を追加する方法です。

私が試してみました1ページ(#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); 
}); 

またsetInterval方法と同様のsetTimeout方法を、使用することができます。

// 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

もう1つの方法は、インターバル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

関連する問題