Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

370
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda