11
$(document).ready(function() {
    var score = 0;

    $("body").mousemove(function() {        
        score++;
        $("#result").val(score);
        console.log(score);
    });

 });

The score will increase every time when I move the mouse, but how should I add a function to decrease the score until 0 when the mouse is not moving?

jming
  • 110
  • 8
Roger Liao
  • 111
  • 4

2 Answers2

8

You could set an interval that decreases the value if the mouse does not move, and clear it when it moves, and reset it, something like this:

$(document).ready(function() {
    var score = 0, decreaseInterval, intervalTime = 1000;

    function decrease() {
        if (score > 0) score--;
        $("#result").val(score);
    };

    decreaseInterval = setInterval(decrease, intervalTime);

    $("body").mousemove(function(){
        clearInterval(decreaseInterval);
        score ++;
        $("#result").val(score);
        decreaseInterval = setInterval(decrease, intervalTime);
        console.log(score);
    });
});

Here is a fiddle to demonstrate it working: https://jsfiddle.net/0swrae76/1/

taxicala
  • 21,408
  • 7
  • 37
  • 66
  • Thinking about the JavaScript event loop I don't think you need to clearInterval and setInterval on every mouse move. Intead I would recommend setInterval once and use a boolean flag to manage things. – Sukima May 29 '15 at 00:58
0

Option: Use elapsed time. When the mouse is moved, check now() vs last time mouse was moved. Use elapsed time to decrease the score in a chunk.

Geoffrey Hale
  • 10,597
  • 5
  • 44
  • 45