james james - 8 months ago 19
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() {

function toggleBrand(_this) {

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
as below:

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


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

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


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)

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

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


function foo() { return "value" };

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