使用变量作为 setInterval / setTimeout 中的时间

Use Variable as Time in setInterval / setTimeout

本文关键字:setTimeout 时间 setInterval 变量      更新时间:2023-09-26

这是一个示例情况。

var count,
    time = 1000;
setInterval(function(){
    count += 1;
}, time);

上面的代码将在"count"变量中添加 1,非常 1000 毫秒。似乎 setInterval 在触发时会使用它在执行时看到的时间。如果稍后更新该值,则不会考虑这一点,并且将继续以设置的初始时间触发。

如何动态更改此方法的时间?

使用 setTimeout 代替回调和变量而不是数字。

function timeout() {
    setTimeout(function () {
        count += 1;
        console.log(count);
        timeout();
    }, time);
};
timeout();

在这里演示

较短的版本是:

function periodicall() {
    count++;
    setTimeout(periodicall, time);
};
periodicall();

尝试:

var count,
    time = 1000,
    intId;
function invoke(){
    intId = setInterval(function(){
        count += 1;
        if(...) // now i need to change my time
        {
           time = 2000; //some new value
           intId = window.clearInterval(intId);
           invoke();
        }
    }, time);
}
invoke();

您无法动态更改间隔,因为它设置一次,然后不会再次重新运行 setInterval 代码。那么您可以做些什么来清除间隔并再次将其设置为运行。您也可以使用具有类似逻辑的setTimeout,但使用 setTimeout,您需要每次都注册超时,并且您不需要使用clearTimeout,除非您想在两者之间中止。如果您每次都更改时间,那么 setTimeout 更有意义。

var count,
time = 1000;
function invoke() {
    count += 1;
    time += 1000; //some new value
    console.log('displ');
    window.setTimeout(invoke, time);
}
window.setTimeout(invoke, time);

你不能(据我所知)动态更改间隔。我建议使用回调来做到这一点:

var _time = 1000,
_out,
_count = 0,
yourfunc = function() {
    count++;
    if (count > 10) {
        // stop
        clearTimeout(_out); // optional
    }
    else {
        // your code
        _time = 1000 + count; // for instance
        _out = setTimeout(function() {
            yourfunc();
        }, _time);
    }
};
整数在

JavaScript 中不是通过引用传递的,这意味着无法通过更改变量来更改间隔。

只需取消 setInterval 并使用新时间再次重新启动即可。

示例可以在这里找到:http://jsfiddle.net/Elak/yUxmw/2/

var Interval;
(function () {
    var createInterval = function (callback, time) {
        return setInterval(callback, time);
    }
    Interval = function (callback, time) {
        this.callback = callback;
        this.interval = createInterval(callback, time);
    };
    Interval.prototype.updateTimer = function (time) {
        clearInterval(this.interval);
        createInterval(this.callback, time);
    };
})();
$(document).ready(function () {
    var inter = new Interval(function () {
        $("#out").append("<li>" + new Date().toString() + "</li>");
    }, 1000);
    setTimeout(function () {
        inter.updateTimer(500);
    }, 2000);
});