using jQuery .promise() to call clearInterval()
clearinterval, javascript, jquery, promise, setinterval
Solution
You'll want to use deferreds for this. I wrote an example on jsfiddle a little while ago that may give you some insight.
http://jsfiddle.net/landau/M3Lj4/
From your code, it looks like you are misunderstanding deferreds in general or there isn't enough code here to tell what you are doing. Promises hides `resolving` and `rejecting` functionality
Basically,
var deferred = $.Deferred();
var promise = deferred.promise();
// This will only run once
var timer = setInterval( function () {
deferred.resolve();
}, 1000);
promise.done(function () {
clearInterval( timer );
});
Problem
I have been experimenting a lot with setInterval and clearInterval recently, for creating my own custom effects and one of the things that I have been working on is an efficient way to clear an interval whilst staying out of the global scope. I am trying to improve readability and explore possible performance boosts by using .promise() to call clearInterval() (the below is an example of what I'm trying to do): ``` //caller is a collection of elements function performEffect(caller) { var interval = setInterval(function() { caller.next(); }, 500); caller.promise().done(function() { interval = clearInterval(interval); }); } ``` Up until recently, I had been setting and clearing the interval using an embedded function (example): ``` function performEffect(caller) { var interval; var count = 0; var len = caller.length; if (count >= len) { interval = clearInterval(interval); } var tmr = function () { interval = setInterval(function () { effectFunciton(count++); }, 100); } } ``` P.S. I'm sorry for not posting the original - my versioning system was corrupted. Also, I know that this example is kind of silly, since I could easily use a for-loop or a .each(), but it's just an example - I do have instances where I do not want to use a loop. This is my first post, so I apologize ahead of time if I do something different from the accepted practice. Please let me know if there is anything I can do to improve my posts in the future - I'm always open to constructive criticism :) Thanks!