使用SetTimeout时出现问题

时间:2014-01-05 00:36:10

标签: javascript html

我正在构建游戏并使用Javascript的SetTimeout功能。我想跟踪每次鼠标移动之间的时间,并且我正在使用SetTimeout。问题是,SetTimeout总是每隔x秒调用一次(如SetInterval)。我一直在看这段代码,也许我误读了SetTimeout的文档?

重申一下,我的目标是测量每个鼠标'stoke'之间的时间,并且看起来SetTimeout被称为每隔x毫秒而不是一次。请查看下面的代码以获取更多信息。

同样,我想使用SetTimeout识别鼠标'笔画'。在鼠标“描边”(例如一条线的绘图)之后会有一些暂停(在这种情况下我将其识别为25毫秒)。

<html>
<head>
<title> My Game </title>
<script type="text/javascript">
timeout = null;
document.onmousemove = function(e) {
    var event = e || window.event;
    mouseX = event.clientX;
    mouseY = event.clientY;
    console.log(mouseX+","+mouseY);
    clearTimeout(timeout);
    timeout = window.setTimeout(
        function(){alert("New Mouse Movement")
        },25);
}
</script>
</head>

<body>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

根据我的评论,只有一个空时间。然后移动鼠标时,它将设置开始时间并将计时器设置为0.025秒。如果鼠标继续移动,则它将清除超时并再次启动计时器。如果鼠标停止移动,超时功能将触发并记录移动所花费的时间。

timeout = null;
mouseStart=null;
document.onmousemove = function(e) {
    var event = e || window.event;
    if(mouseStart===null){
        mouseStart=new Date();
    }
    mouseX = event.clientX;
    mouseY = event.clientY;
    console.log(mouseX+","+mouseY);
    clearTimeout(timeout);
    timeout = window.setTimeout(
        function(){
            console.log((new Date()).getTime()-mouseStart.getTime())
            mouseStart=null;
        },25);
}

小提琴,将鼠标移动一圈,一旦停止,您将获得鼠标移动的经过时间,以毫秒为单位(+25毫秒):http://jsfiddle.net/rr4g2/

注意 25毫秒是hella fast。您可能需要300毫秒的时间才能使鼠标停止移动更加清晰。

答案 1 :(得分:0)

你在发生25分钟后alert进行新的鼠标移动,而不是计算每个移动间隔多长时间。 setTimeout不是您所需要的。

相反,在每次鼠标移动时保存当前时间并从中扣除之前的时间,然后alert

修改:我已alert替换console.log,因为mousemove会经常运行。

var oldTime = Date.now();
document.onmousemove = function (e) {
    var event = e || window.event;
    mouseX = event.clientX;
    mouseY = event.clientY;
    console.log(mouseX+","+mouseY);
    // Get the current time.
    var newTime = Date.now();
    // Alert the difference.
    console.log('Time between mouse strokes: ' + (newTime - oldTime) + 'ms');
    // Save the current time for the next movement.
    oldTime = newTime;
};
相关问题