Better setInterval() in jQuery

by b9chris

HTML

<div>Blinking!</div>

CSS

div {
    width: 100px; height: 100px;
    background: #000;
    color: #fff;
}
body {
    font: 10pt Verdana;
}

JavaScript

/**
 * Alternative to window.setInterval(), that plays nicely with modern animation and CPU suspends
 */
$.setInterval = function (fn, interval) {
	var body = $('body');
	var queueInterval = function () {
		body
		.delay(interval)
		.queue(function(dequeue) {
			fn();
			queueInterval();
			dequeue();	// Required for the jQuery animation queue to work (tells it to continue animating)
		});
	};
	queueInterval();
};

$.setInterval(function() {
    $('div').fadeOut().fadeIn();
}, 2000);