Skip to content

Instantly share code, notes, and snippets.

@onurkerimov
Last active October 9, 2018 11:58
Show Gist options
  • Save onurkerimov/1c69bdbd33890a5b1e5ffbea7e6b4142 to your computer and use it in GitHub Desktop.
Save onurkerimov/1c69bdbd33890a5b1e5ffbea7e6b4142 to your computer and use it in GitHub Desktop.
A practical setInterval function wrapper that I oftenly use, in which the interval is cleared when the callback function returns true.
(function() {
$.setInterval = function(int, fn) {
var returnValue
var interval = setInterval(function() {
if (returnValue === true) {
clearInterval(interval);
} else {
returnValue = fn()
}
}, int)
return interval
};
}());
@onurkerimov
Copy link
Author

Instead of the following routine:

var i = 0;
var myInterval = setInterval(function() {
    // something to be done 10 times, with 1000 millisecond period
    i++;
    if(i>10) {
        clearInterval(myInterval)
    }
}, 1000)

easily:

var i = 0;
$.setInterval(1000, function() {
    // something to be done 10 times, with 1000 millisecond period
    i++;
    if(i>10) { return true; }
})

Pros:

  • Never write "clearInterval" again.
  • Never create variables such as "myInterval"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment