2

I'm having a trouble with running function for checking new messages in table. When I open the message_page I want this 'setInterval' function to start running, but after leaving the page stop running (I have one html file with multiple pages). Is there a way to do that? Because my script keeps running even after leaving the page.

$(document).on('pageshow', '#message_page', function(){
    $('#chat_box').scrollTop($('#chat_box').height());

    setInterval( function() {checkNewMessages(c_key,m_fid);},1000);
});
Gajotres
  • 57,309
  • 16
  • 102
  • 130
Jakub Zak
  • 1,212
  • 6
  • 32
  • 53

1 Answers1

4

Here's a working example: http://jsfiddle.net/Gajotres/QUCUt/

$(document).on('pagebeforeshow', '#index', function(){       
    timerHandler.timer1 = setInterval(function () {
        $('#test-input').val(parseInt($('#test-input').val()) + 1);
    }, 1000);
});

$(document).on('pagebeforehide', '#index', function(){       
    clearInterval(timerHandler.timer1);
});

var timerHandler = {
    timer1 : null
}

Let me explain. If you create a timer as a object variable, it can be accessed at any moment. In this case pagebeforeshow event will start timer and pagebeforehide will pause it. You can test it on my example, just let it run a little bit, then go to the second page, wait a bit and return back. You will see that timer has been paused.

Gajotres
  • 57,309
  • 16
  • 102
  • 130
  • 1
    Thx man, this did the trick, had no idea there is pagehide/pagebeforehide at all... :) – Jakub Zak Apr 01 '13 at 15:21
  • 1
    If you have time take a look at my other answer, there you will find a full list of jQM page events: http://stackoverflow.com/a/14469041/1848600 – Gajotres Apr 01 '13 at 15:22
  • in this post you mentioning you can get data from previous page, can you also find out which id of the page was the previous page? So for example, some specific function would be triggered on pagebeforeshow of a page, if previous page was "xyz", if not trigger different function? – Jakub Zak Apr 01 '13 at 17:04
  • 1
    $('#index').live('pagebeforeshow', function (e, data) { alert(data.prevPage.attr('id')); }); – Gajotres Apr 01 '13 at 17:06
  • problem is if I'm trying to put the ID of a page into variable, there is an error in console: Uncaught ReferenceError: data is not defined, that is at the line with code assigning id attribute to variable. – Jakub Zak Apr 01 '13 at 19:38
  • prevPage = data.prevPage.attr('id'); this is what I'm trying to use. – Jakub Zak Apr 01 '13 at 19:39
  • Here's a working example: http://jsfiddle.net/Gajotres/mfC8j/ few things to consider, it must be executed inside a pagebeforeshow and pageshow event and data parameter must be passed through the event function. – Gajotres Apr 01 '13 at 19:42