2015-06-12 32 views
1

我需要使用setTimeout或setInterval做一些事情,不能使它工作。可以說我有一個圖像,當窗口完成渲染,用戶保持空閒和/或在20秒內做事情,並在20秒後通過用戶做出某些事情(點擊,移動或滾動)時,我想要加載刷新圖像,但如果時間爲20秒,並且用戶空閒,我希望繼續計算直到用戶進行交互的時間,然後再清除該值並重新開始觀看。setTimeout與條件再次運行之前內部

例:

  • 圖片負載,用戶移動,保持(在20秒此全部)空閒,點擊,則用戶使得那些在20秒後的相互作用,因此圖像刷新,的setTimeout或setInterval的清零並重新開始

  • 圖像加載,用戶移動,保持空閒(所有這些在20秒內),然後用戶在這20秒後保持空閒,所以圖像不刷新,setTimeout或setInterval繼續計數而不是清除等待用戶再次啓動互動

反正我無法做出這個方法。

我有這樣的事情這是不工作:

var refresh = setTimeout(function(){ 
    console.log('Inside waiting for user interaction'); 
    //If user is idle while inside here keep waiting and counting 

    $(document).on('mousemove click', function(){ 
     console.log('Inside because of user interaction'); 
     //Refresh image and then clearTimeOut 
     clearTimeout(refresh); 
     //Start again waiting for 20 seconds to get inside 
     setTimeout(refresh); 
    }); 
}, 20000); //20 seconds before waiting for user interaction 

非常感謝!

+0

換句話說,你只需要在20秒後要考慮的活動? –

+0

你正在多次添加事件監聽器 – trebor

+0

@RoyJ,我把描述複雜的抱歉哈哈。我想要那個! – arbustobce

回答

-1

有一個標誌來指示計時器是否已經過去,並在處理鼠標活動時檢查該標誌。

var elapsed, timer; 

function refresh() { 
    //... stuff you want to do ... 
    resetTimer(); 
} 

function resetTimer() { 
    if (!elapsed) { 
     clearTimeout(timer); 
    } 
    elapsed = false; 
    timer = setTimeout(function() { 
     elapsed = true; 
    }, 10000); 
} 

function mouseActivity() { 
    if (elapsed) refresh(); 
} 

演示小提琴:http://jsfiddle.net/7768nbze/

+0

當然有一些人渴望在沒有評論的情況下降低工作答案。 –

+0

@arbustobce這是做你想做的嗎? –

+0

抱歉不能回覆之前,我只是嘗試了您的代碼,添加了我需要的額外部件,並且它的工作非常流暢,非常感謝! 還要感謝humble.rumble幫助我,你們倆都很棒,繼續保持! :d – arbustobce

相關問題