Reputation: 63
I want to use webworker to detect my idle time.
I'm writing some code. What else do I need to add so that my counter restart on mouse move or key press?
I'm new to coding. Please help. Here is my code:
<ul id="message-list"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var worker = new Worker('demo.js');
worker.onmessage = function(e){
var message =e.data;
$('#message-list').append('<li>'+message+'</li>');
}
</script>
This is my main HTML file and demo.js is below :
var idleTime = 0;
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement() {
idleTime = idleTime + 1;
self.postMessage( idleTime);
if (idleTime == 15) { // 15 seconds
self.close();
}
}
In this code loop will run for 15 seconds then worker will terminate. What I want is this loop will again start from 0 if I move my mouse or press any key on keyboard.
Upvotes: 4
Views: 1435
Reputation: 1223
Since web workers do not have access to DOM, you can post a message to your worker from your main thread when a key is pressed or on mouse move:
$(document).keypress(function(e){
worker.postMessage({
type: 'KEYPRESS',
keycode: e.which
});
});
And in your woker listen to the message:
self.onmessage = function(msg) {
switch (msg.data.type) {
case 'KEYPRESS':
console.log("Key pressed");
idleTime = 0;
break;
}}
Upvotes: 1