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

查看:252
本文介绍了在运行时更改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 *计数器等于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天全站免登陆