存储 setInterval 以便稍后清除
我正在开发一个利用 JavaScript 间隔的 jQuery 插件。但是,当再次使用参数 running
为 false
调用插件时,我希望清除在该特定 DOM 元素上调用的先前间隔。
这是一些简短的代码:
(function ($) {
$.fn.examplePlugin = function (running) {
return this.each(function () {
if (running === false) {
// Clear the previous interval assigned to this DOM element
} else {
setInterval(function () {
// Interval code
}, 50);
}
return this;
});
};
})(jQuery);
这怎么可能?我想过使用全局变量来存储间隔,但我真的不想这样做。我也不知道如何为特定 DOM 元素分配间隔。
I'm working on a jQuery plugin that utilises JavaScript intervals. However, when the plugin is called again with the argument running
as false
, then I want the previous interval called on that particular DOM element to be cleared.
Here is some shortened code:
(function ($) {
$.fn.examplePlugin = function (running) {
return this.each(function () {
if (running === false) {
// Clear the previous interval assigned to this DOM element
} else {
setInterval(function () {
// Interval code
}, 50);
}
return this;
});
};
})(jQuery);
How is this possible? I thought of using global variables to store the intervals but I don't really want to do that. I also don't have any clue how to assign an interval to a particular DOM element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果你想保存每个 DOM 元素的间隔,那么你最好使用
.data( )
,这正是您想要的 - 在特定 DOM 元素上设置数据。If you want to save intervals per DOM element, then you'd be best off with
.data()
, which does exactly what you want - setting data on a particular DOM element.