Handy JavaScript Polling Function for Resize and Other Events

I use JavaScript quite often, and a frequent need is for me to poll when a screen is resized and fire some code (or event) at particular intervals.

This is often called “polling”, and I’ve created a handy JS function that you can use for all of your polling needs. Here is the polling variable function:

This variable takes a function and applies another function and polling timer based on parameters set. I use this most commonly with the window.resize event, so here is an example of how you would use this (I’m using jQuery here):

Here we poll the window.resize event every 25ms and fire our anonymous function that is passed into the poll variable. We can check for flags and other things before doing anything if necessary.

This function always comes in handy, so I hope you can make use of it too!

Enjoy? See Inside my WordPress Toolbox

Over 20,000 people have purchased my WordPress products. Get absolutely FREE access to regular updates and my toolbox - a collection of WordPress-related products and resources that every WordPress professional should own.

  • http://vugujranwala.com/Download/pastPapers/index.php?v=1&csid=CS201 wasifaliwasi

    A very awesome ! blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. I was exactly searching for. Thanks for such post and please keep it up.

  • http://portal2web.biz Joseph Levin


    Your post is exactly what I need to cut down on extraneous repaints caused by excessive firing of scroll, resize and mouse-move type of events.

    I was hoping if you could verify for me if I’m understanding things correctly-

    It looks like every time the resize event is fired, the poll function is called, and it clears the timer’s setTimeout every time; the timer’s setTimeout in-turn would run the callback after 25ms have elapsed.

    This clearing of the timer’s setTimeout (occurring when the poll function fires) happens a lot quicker than the preferred execution time of the callback function (the 25ms) such that the callback function won’t have the time to be able to fire unless the user stops causing the resize event to fire.

    If the user-caused resize event could by some miracle be called just once, executing the poll function would first clear the existing timer’s setTimeout and then would run the callback after the 25ms.

    The timer variable is separately scoped to each instance of the poll function that is called so that multiple instances of the poll function may be called, say to handle onResize, onScroll, or onMousemove, and the setTimouts won’t interfere with each other.

    Am I fully understanding what the code is doing?

    My apologies for being long-winded. Thank you for your time!