开发者

Run function only after event handler triggered

开发者 https://www.devze.com 2023-01-31 12:39 出处:网络
I need to continuously fetch new data every 5 minutes, but only if the user is active on th开发者_开发技巧e page.

I need to continuously fetch new data every 5 minutes, but only if the user is active on th开发者_开发技巧e page.

Here's my progress/thoughts so far:

  1. When the document is loaded, get the data and use the setTimeout method to essentially sleep a function for 5 min.
  2. After 5 min, the function will run, but only update the data if the user mouseovers a section of the page.

    setTimeout(getData, 10000) // Shortened time for testing purposes
    function getData(){
        $('#feed').mouseover(function(){
            $('#feed').fadeOut();
            Get the feed
            setTimeout(getData, 10000);
        });
    }
    

Is there a better way of doing this?


There may be a better way but for this example you will need to unbind the .mouseover like so:

setTimeout(getData, 10000) // Shortened time for testing purposes
function getData(){
    $('#feed').mouseover(function(){
        $('#feed').fadeOut();
        Get the feed
        $(this).unbind('mouseover');
        setTimeout(getData, 10000);
    });
}

Otherwise the event will still be bound and you'll keep calling the feed regardless of the timeout


Based on @Jacob's answer, you could use a flag and after some time, set it to false. You could keep your function that gets the data running in background and check that flag:

var active = true;
var current_timeout = null;

function idle() {
    active = false;
    current_timeout = null; 
}


$('#feed').mousemove(function(){ 
    // maybe another event that does not 
    // constantly fire (but often enough) is enough

    active = true;
    if(current_timeout !== null) {
        window.clearTimeout(current_timeout);
    }
    timeout = window.setTimeout(idle, 180000); // mark not active after 3 minutes
});

window.setInterval(function() {
    if(active) {
        //get data
    }
), 300000);

I'm not sure though if it not too unnecessary to have the interval run although the user is not on the page (although it won't do anything as long as active is false). You have to test that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号