Search code examples
javascriptjquerydelaysettimeout

Add delay to JS function


I have this function:

$(document.body).ready(function() {
  var o = $(".hidden");
  $(".about_us").click(function() {
    o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible");
  });
});

and I want to add a delay to it. I'm trying the

setTimeout(...); 

like this

$(document.body).ready(function() {
  setTimeout(function() {
    var o = $(".hidden");
    $(".about_us").click(function() {
      o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible");
    });
  }, 1000);
});

but it's not working. Any help?


Solution

  • It looks like you are trying to add timeout 1 second before adding the click listener, but as @Moob said, it doesn't make sense.

    If you want the delay to happen after the click, this code will work:

    $(document).ready(function() {
      $(".about_us").click(function() {
        setTimeout(function() {
          var o = $(".hidden");
          o.hasClass("visible") ? o.removeClass("visible") : o.addClass("visible");
        }, 1000);
      });
    });