setInterval(function(),time)在运行时更改时间

alt*_*gan 3 javascript jquery

我想在代码运行时更改setInterval函数时间.

我试试这个

<script type="text/javascript">
        $(function () {
            var timer;
            function come() { alert("here"); }
            timer = setInterval(come, 0);
            clearInterval(timer);
            timer = setInterval(come, 10000);
        });
    </script>
Run Code Online (Sandbox Code Playgroud)

第一个SetInterval不起作用!

ade*_*neo 13

你正在清除下一行的间隔,所以第一行不会工作,因为它立即被清除:

        timer = setInterval(come, 0);
        clearInterval(timer);
        timer = setInterval(come, 10000);
Run Code Online (Sandbox Code Playgroud)

另外,正如gdoron所说,设置一个空间的间隔并不是真正有效,也不是一个好主意,而是使用setTimeout,或者只是在不需要延迟的情况下直接运行该函数.

        come();
        clearInterval(timer);
        timer = setInterval(come, 10000);
Run Code Online (Sandbox Code Playgroud)


Ber*_*rgi 7

你不能。您将需要使用 setTimeout,并重复调用它:

var timer; // current timeout id to clear
function come(){ /* do something */};
var time; // dynamic interval

(function repeat() {
    come();
    timer = setTimeout(repeat, time);
})();
Run Code Online (Sandbox Code Playgroud)

有了这个,您可以设置每次repeat执行函数时要应用的不同“间隔” 。但是,如果time在超时期间更改没有任何变化,您需要为此停止超时。