简体   繁体   English

SetInterval继续调用相同的函数

[英]SetInterval keeps calling same function

I have this function: 我有这个功能:

original = 0;
original = original+1;
setInterval("dis"+original+"();", 2400);

But there is a problem, every time it is called it appears to be calling the same function over again... They're not calling individual functions. 但是有一个问题,每次调用它似乎都在再次调用同一个函数……他们没有在调用单个函数。

Thanks for your help. 谢谢你的帮助。

You need to regenerate the function name every time as setInterval doesn't take care of that for you - it always runs the code that was passed to it when it was set up. 您每次需要重新生成函数名称,因为setInterval不会为您解决这个问题-它总是运行设置时传递给它的代码。

This will find the correct function in global scope ( window ) and call it: 这将在全局范围( window )中找到正确的函数并调用它:

original = 0;
original = original+1;
setInterval(function(){
    window["dis" + original]();
    original++;
}, 2400);

Incrementing the counter also needs to be done in the setInterval handler. 计数器的递增也需要在setInterval处理程序中完成。

It's because of the fact that original is used to construct the callback function name once - and only once - to call setInterval . 这是因为事实是使用original一次构造了回调函数名称(并且一次只能构造一次)来调用setInterval As the name suggests, setInterval sets a callback once and continues executing until you clear the interval with clearInterval . 顾名思义, setInterval设置一次回调,然后继续执行,直到使用clearInterval清除间隔为止。

If you like to change the method beeing called, you could try setTimeout , ie: 如果您想更改beeing调用的方法,可以尝试setTimeout ,即:

var original = 0,
    cb = function() {
        ('dis' + original).prototype.call(null);
        original++;
        setTimeout(cb, 2400);
    }
cb();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM