如何在javascript中将intervalID传递给interval函数? [英] How to pass intervalID to interval function in javascript?
问题描述
在javascript中创建一个间隔时,我想从函数内部停止间隔,但我不想像这样从外部引用ID值
In javascript when I create an interval, I want to stop the interval from inside the function, but I don't want to reference the ID value from outside like this
var y = setInterval(function(){ clearInterval(y); }, 1000);
我想要的是传递一个类似于这种风格的变量
What I want is to pass a variable similar to this style
setTimeout(function(data){alert(data);}, 1000, "data");
这也适用于setInterval,除了我无法真正传递setInterval返回的id值函数,因为它在调用后被创建。
This works for setInterval too, except I can't really pass the id value that's returned by the setInterval function, because it gets created after calling it.
现在我正在做这样的黑客攻击:
Right now I'm doing a hack like this:
var r = [];
var y = setInterval(function(r){ if (r.length==1) { clearInterval(r[0]); } }, 1000, r);
r.push(y);
有没有人知道正确的方法?
Does anyone know the right way?
谢谢
推荐答案
你必须使用返回值,但这并不意味着变量需要被任何东西访问其他;只是封装:
You have to use the return value, but that doesn't mean that the variable needs to be accessible to anything else; just encapsulate:
(function() {
var y = setInterval(function(){ clearInterval(y); }, 1000);
})();
y
只有才能在外部匿名函数中访问,该函数只有间隔函数而且没有其他内容。
y
in the above is only accessible within the outer anonymous function, which only has the interval function and nothing else in it.
你甚至可以给自己一个可重复使用的 setInterval
包装器来执行它:
You could even give yourself a reusable setInterval
wrapper to do it:
function setIntervalWrapper(callback, time) {
var args = Array.prototype.slice.call(arguments, 1);
args[0] = setInterval(function() {
callback.apply(null, args);
}, time);
}
这会将时间句柄作为第一个参数传递给任何其他人你指定。它还具有可靠地跨浏览器支持这些后续参数的好处(一些旧的浏览器不支持将参数传递给回调)。
That will pass the time handle as the first argument, in front of any others you specify. It also has the benefit of supporting those follow-on arguments reliably cross-browser (some older browsers didn't support passing arguments to the callback).
无端示例:
function setIntervalWrapper(callback, time) {
var args = Array.prototype.slice.call(arguments, 1);
args[0] = setInterval(function() {
callback.apply(null, args);
}, time);
}
var counter = 0;
setIntervalWrapper(function(handle, arg1, arg2) {
snippet.log("Interval callback called, handle is " + handle + ", args are '" + arg1 + "' and '" + arg2 + "'");
if (++counter > 5) {
clearInterval(handle);
}
}, 500, "a", "b");
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
这篇关于如何在javascript中将intervalID传递给interval函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!