在setInterval / setTimeout中使用变量作为时间 [英] Use Variable as Time in setInterval / setTimeout

查看:128
本文介绍了在setInterval / setTimeout中使用变量作为时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个示例情况。

var count,
    time = 1000;

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

上面的代码将countvar加1,非常1000毫秒。
似乎setInterval在被触发时将使用它在执行时看到的时间。
如果该值稍后更新,则不会将此考虑在内,并将继续以设置的初始时间触发。

The code above will add 1 to the "count" var, very 1000 milliseconds. It seems that setInterval, when triggered, will use the time it sees on execution. If that value is later updated it will not take this into account and will continue to fire with the initial time that was set.

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

How can I dynamically change the time for this Method?

推荐答案

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

Use setTimeout instead with a callback and a variable instead of number.

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

演示这里

Demo here

更短版本将是:

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

这篇关于在setInterval / setTimeout中使用变量作为时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆