Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

369
Views
jQuery: Delay a function from being used again once fired for a set time

I want my function to fire on scroll, but then wait 250ms until it may fire again.

function myFunction() {
    console.log('hello');
}

$(window).on('scroll', function() {
        myFunction();
});

I have tried a timeout:

$(window).on('scroll', function() {
    setTimeout(function() {
        myFunction();
    }, 250);
});

However this method delays for 250ms before firing the function.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Based on this answer, you can add a flag so that additional events are not fired, then clear that flag using a timeout.

Note that this will lose/drop events within the timeout, so should not be used for something like user keyboard input; where debounce would be more suitable.

var active = false;

$(window).on('scroll', function() {
    if (active) return;
    active = true;
    
    myFunction();
    setTimeout(function() {
        active = false;
    }, 250);
});

function myFunction() { console.log("scroll"); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style='height:30000px;'>
something to scroll
</div>

This is a basic throttle implementation. Improvements would be to make it modular / namespace'd and/or store the "active" flag on the element itself; so that it the same event can be reused for multiple elements and doesn't create lots of global variables.

about 4 years ago · Juan Pablo Isaza Report

0

Simply call your function once outside of setTimeout.

$(window).on('scroll', function() {
    myFunction(); // call once

    setTimeout(function() {
        myFunction();
    }, 250); // repeat call after 250ms
});

Use setInterval instead of setTimeout if you want repeated calls every 250ms.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!