在运行时更改 SetInterval 的间隔 [英] Changing the interval of SetInterval while it's running

查看:31
本文介绍了在运行时更改 SetInterval 的间隔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 javascript 函数,它使用 setInterval 每十分之一秒操作一个字符串,进行一定次数的迭代.

I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.

function timer() {
    var section = document.getElementById('txt').value;
    var len = section.length;
    var rands = new Array();

    for (i=0; i<len; i++) {
        rands.push(Math.floor(Math.random()*len));
    };

    var counter = 0
    var interval = setInterval(function() {
        var letters = section.split('');
        for (j=0; j < len; j++) {
            if (counter < rands[j]) {
                letters[j] = Math.floor(Math.random()*9);
            };
        };
        document.getElementById('txt').value = letters.join('');
        counter++

        if (counter > rands.max()) {
            clearInterval(interval);
        }
    }, 100);
};

我想在每次运行时根据计数器更新它,而不是将间隔设置为特定数字.所以,而不是:

Instead of having the interval set at a specific number, I would like to update it every time it runs, based on a counter. So instead of:

var interval = setInterval(function() { ... }, 100);

应该是这样的:

var interval = setInterval(function() { ... }, 10*counter);

不幸的是,这不起作用.好像10*counter"等于0.

Unfortunately, that did not work. It seemed like "10*counter" equals 0.

那么,如何调整匿名函数每次运行的时间间隔?

So, how can I adjust the interval every time the anonymous function runs?

推荐答案

改用 setTimeout().然后回调将负责触发下一次超时,此时您可以增加或以其他方式操纵时间.

Use setTimeout() instead. The callback would then be responsible for firing the next timeout, at which point you can increase or otherwise manipulate the timing.

这是一个通用函数,可用于为任何函数调用应用减速"超时.

Here's a generic function you can use to apply a "decelerating" timeout for ANY function call.

function setDeceleratingTimeout(callback, factor, times)
{
    var internalCallback = function(tick, counter) {
        return function() {
            if (--tick >= 0) {
                window.setTimeout(internalCallback, ++counter * factor);
                callback();
            }
        }
    }(times, 0);

    window.setTimeout(internalCallback, factor);
};

// console.log() requires firebug    
setDeceleratingTimeout(function(){ console.log('hi'); }, 10, 10);
setDeceleratingTimeout(function(){ console.log('bye'); }, 100, 10);

这篇关于在运行时更改 SetInterval 的间隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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