setInterval在行动下改变速度

时间:2013-09-22 13:10:17

标签: javascript performance time settimeout setinterval

我不知道如何在setInterval中的函数工作时改变速度..

在代码中:

var timeout, count = 0, speed = 5000;

                  $('#stage').mousedown(function() {
                    timeout = setInterval(function() {
                        speed = parseInt(speed / 1.3); // HERE I want change speed
                        create(speed); // Some Function
                    }, speed); // This speed, I don't know how to change
                });

                $('#stage').mouseup(function() {
                    count = 0;
                    clearInterval(timeout);
                });

这项工作但速度超出函数是const(5000)

非常感谢所有帮助!

2 个答案:

答案 0 :(得分:1)

您必须使用命名函数才能将其传递给新的setTimeout函数。

var speed = 5000;
var timer;

$('#stage').mousedown(function() {
    timer = setTimeout(handleTick, speed);
});

$('#stage').mouseup(function() {
    clearTimeout(timer);    
});

var handleTick = function () {
    speed = parseInt(speed / 1.3);
    timer = setTimeout(handleTick, speed);
};

答案 1 :(得分:0)

据我所知,您无法在致电setInterval后更改延迟。但是,您可以以递归方式调用setTimeout

var speed = 5000;

function doSomething() {
    console.log(speed); // prints from 5000 to 1000
    speed -= 1000;
};

setTimeout(function () {
    doSomething(); // changes the global "speed" var internally
    speed && setTimeout(arguments.callee, speed);
}, speed);