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.

有帮助吗?

解决方案

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.

var saved = $(this).data("__examplePlugin_interval");

if (saved) { // I think you mean when it *is* running
    clearInterval(saved);
    $(this).removeData("__examplePlugin_interval");
} else {
    var interval = setInterval(function () {
        // Interval code
    }, 50);

    // choose a name that won't be accidentally overwritten by others
    $(this).data("__examplePlugin_interval", interval);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top