james james - 4 months ago 8
jQuery Question

How to execute an animation, wait 5 seconds, then do it again?

I have a simple tile. Upon click, the tile gets filled in with content B instead of content A, and on click again, the tile gets filled back in with content A instead of content B.

This is the jQuery code:

$(".switch").on('click', function() {
toggleBrand($(this));
})

function toggleBrand(_this) {
_this.children().not(".no-display").toggle();
_this.children(".no-display").toggle();
}


What I would now like is for the second "click" to happen automatically. I.e., when you click the object, content B shows instead of A, then there's a 2 second delay, and content A shows instead of content B again without you having to click.

I tried using a
setTimeout
as below:

$(".switch").on('click', function() {
_this = $(this)
toggleBrand(_this);

setTimeout(toggleBrand(_this),2000);
})


But the fiddle breaks with a
setTimeOut undefined
even though I cased it correctly... Am I not using
setTimeout
correctly?

Fiddle here: https://jsfiddle.net/v018hh52/2/

Answer

Yes, you are using setTimeout wrong

You are passing the return value of the function, instead you should pass a function.

$(".switch").on('click', function() {
  _this = $(this)
  toggleBrand(_this);

  setTimeout(function() { toggleBrand(_this) },2000);

  // OR, thanks @4castle for his comment
  setTimeout(toggleBrand, 2000, _this);
})

Explanation

function foo() { return "value" };

foo // -> function
foo() // -> "value"
Comments