【问题标题】:setInterval change speed under actionsetInterval 变化速度作用下
【发布时间】:2013-09-22 13:10:16
【问题描述】:

我不知道如何在 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)

非常感谢大家的帮助!

【问题讨论】:

标签: javascript performance time settimeout setinterval


【解决方案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);
};

【讨论】:

  • 这永远不会停止!在handleTick函数中调用setTimeout时,需要重新设置定时器,否则clearTimeout不起作用。
【解决方案2】:

据我所知,您无法更改致电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);

【讨论】:

  • arguments.callee 已弃用。最好使用命名函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-08
  • 2019-10-26
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2023-03-10
相关资源
最近更新 更多