【问题标题】:Change setInterval value dynamically动态更改 setInterval 值
【发布时间】:2015-06-09 07:23:25
【问题描述】:

我想动态更改 setInterval 的间隔值。由于 setInterval 回调函数中存在循环,我正在苦苦挣扎。我在stackoverflow上看到了太多问题。但是没有任何解决方案可以帮助我。如果有人知道答案,请举例说明。谢谢你。 这是我的代码。

<html>
<head>
    <script type="text/javascript">
        var speed = 10;
        function updateSlider(slideAmount) {
            speed = slideAmount;
        }
        function load() {
            downloadUrl("points.xml", function (data) {
                /* code */
                abc();
            });
            function abc() {
                function track() {
                    /* code */
                    downloadUrl("points.xml", function (data) {
                        var xml = data.responseXML;
                        var points = xml.documentElement.getElementsByTagName("point");
                        var i = 0;
                        setInterval(function () {
                            if (i != points.length) {
                                alert(speed);
                            }
                            i++;
                        }, 100 * speed);
                    });
                }
                track();
            }
        }
        function downloadUrl(url, callback) {
            var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
            request.onreadystatechange = function () {
                if (request.readyState == 4) {
                    request.onreadystatechange = doNothing;
                    callback(request, request.status);
                }
            };
            request.open('GET', url, true);
            request.setRequestHeader("Content-type", "text/xml");
            request.send(null);
        }
        function doNothing() {
        }
    </script>
</head>
<body onload="load();">
    <div id="slider">
        5% <input id="slide" type="range" min="1" max="20" step="5" value="10" onchange="updateSlider(this.value)" /> 200%
    </div>
    <div id="chosen">10</div>
</body>

【问题讨论】:

  • 一旦设置了间隔,就无法更改,但可以使用clearInterval 停止并重置。根据您的需要,使用setTimeout 并使用更改后的超时值再次重复设置。
  • 你可能想看看this answer

标签: javascript callback setinterval


【解决方案1】:

诀窍是不要使用setInterval,而是在循环中使用setTimeout

setInterval 读取你给它的时间值一次,根据这个时间安排,然后忘记它。你唯一能做的就是clearInterval(myInterval),如果你已经将你的时间间隔分配给了一个像myInterval这样的变量。

setTimeout 非常相似,只是我们可以使用它手动循环相同的函数。手动循环允许我们在每次超时后更改setTimeout 的时间。

这是一个简单的例子。将滑块向左移动会使滴答声更快,向右移动则更慢。

DEMO

var timing = 250,
    i = 0,
    output = document.getElementById('output');

function loop() {
  i++;
  output.innerHTML = i;
  window.setTimeout(loop, timing);
}

document.querySelector('input[type="range"]').addEventListener('change', function (e) {
  timing = parseInt(this.value);
});

loop();
<input type="range" min="100" max="500" value="250" />
<div id="output"></div>

附带说明:使用这种模式几乎总是比使用setInterval 更好的选择。 setInterval 运行您的函数执行可能需要比间隔持续时间更长的机会。如果您在函数中最后调用 setTimeout,则循环 setTimeout 永远不会发生这种情况。

文档:

【讨论】:

    【解决方案2】:

    这是我一直使用的没有 setInterval 的版本:

    function timer()
    {
        var timer = {
            running: false,
            iv: 5000,
            timeout: false,
            cb : function(){},
            start : function(cb,iv,sd){
                var elm = this;
                clearInterval(this.timeout);
                this.running = true;
                if(cb) this.cb = cb;
                if(iv) this.iv = iv;
                if(sd) elm.execute(elm);
                this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
            },
            execute : function(e){
                if(!e.running) return false;
                e.cb();
                e.start();
            },
            stop : function(){
                this.running = false;
            },
            set_interval : function(iv){
                clearInterval(this.timeout);
                this.start(false, iv);
            }
        };
        return timer;
    }
    

    用法:

    var timer_1 = new timer();
    timer_1.start(function(){
        //magic here
    }, 2000, false);
    
    var timer_2 = new timer();
    timer_2.start(function(){
        //more magic here
    }, 3000, true);
    
    //change the interval
    timer_2.set_interval(4000);
    
    //stop the timer
    timer_1.stop();
    

    如果函数需要在 0 处运行,则 start 函数的最后一个参数是布尔值。

    你也可以在这里找到脚本:https://github.com/Atticweb/smart-interval

    【讨论】:

      【解决方案3】:

      这是动态更新间隔的另一种简单方法。

      var intv_sec = 1500; // Initial interval in milliseconds
      var speed = 1.5; // Multiplier
      
      function chk_fn(){
        // Your code here
        console.log(intv_sec);
        
        
        // Reset and update interval
        clearInterval(chkh);
        intv_sec = intv_sec*speed;
        chkh = setInterval(chk_fn, intv_sec);
      }
      
      var chkh = setInterval(chk_fn, intv_sec);

      【讨论】:

        猜你喜欢
        • 2016-05-28
        • 1970-01-01
        • 2017-04-18
        • 2021-01-27
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多