Wednesday, 6 March 2013

Adding a delay within a jQuery each()

Well isn't that annoying! I've just spent 30 minutes trying to introduce a delay within a jQuery each call so that each request is delayed by a little bit. I guess my original Google-fu was pants though as I racked my brains until I finally came up with this:

$(".clickMe").each(function(k, v){
    var $this = this;
    setTimeout(function(){
        myfunction($this)
    }, (k + 1) * 200);
});

Then, as I was congratulating myself on my coolness, I did a search and discovered that Rob came to much the same conclusion as I on stackoverflow.

I know why it works as well. I originally had it differently but all things then just ran as one after the delay and that's because JavaScript is non-blocking. The solution is to set up a number of function calls and add lengthening delays to the setTimeout. Then JavaScript could add them to it's list of things to do in the future without worrying.

Here's a jsfiddle to demo it.

No comments:

Post a Comment