1

I want to add and remove a class to a div on the basis of time. It should add a class after 6 secs and remove it after 4 secs. I tried a basic implementation. why isn't this working? I assume the problem is two setTimeouts together like this. If I comment out the second line the first one works. What is happening here?

setTimeout(addHighlight(), 6000);
setTimeout(removeHighlight(), 10000);

Can somebody show me how i can write a single function that does both(add and remove class) on the basis of a delay parameter?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
anoop chandran
  • 1,460
  • 5
  • 23
  • 42
  • Try `setTimeout(function() { addHighlight(); setTimeout(function() { removeHighlight() }, 4000) }, 6000);` – Abhi May 26 '17 at 08:18

2 Answers2

7

Try this:

setTimeout(function() {
  $('#square').addClass('highlight');
}, 6000);

setTimeout(function() {
  $('#square').removeClass('highlight');
}, 10000);

https://jsfiddle.net/js6wh78h/8/

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
-2

This is probably what you want to do:

setTimeout(function(){
  $("#test").addClass('on');
  
  setTimeout(function(){
     $("#test").removeClass('on');
  }, 4000);
}, 6000);
.on {
  background: lime;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">hello world</div>

The first timeout executes after 6 seconds, adds a class to the div and starts another timeout, wich executes after 4 seconds and removes the class.

Robert
  • 426
  • 1
  • 4
  • 11