Issue lies in the timing, once the brFun
function adds the class, the timeout triggers to remove it immediately due to both actions happening at a 2-second
interval
$(document).ready(function () {
function brFun() {
$('div').addClass('br');
setTimeout('$(\'div\').removeClass(\'br\')', 2000)
};
setInterval(brFun, 4000);
});
$(document).ready(function() {
function brFun() {
$('div').addClass('br');
setTimeout('$(\'div\').removeClass(\'br\')', 2000)
};
setInterval(brFun, 4000);
});
.br {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>soemt message</div>
Let's solve this without relying on the second timer
$(document).ready(function () {
var $div = $('div');
function brFun() {
if ($div.hasClass('br')) {
$div.removeClass('br');
} else {
$div.addClass('br');
}
};
setInterval(brFun, 2000);
});
Demo: Fiddle
For a more concise solution
$(document).ready(function () {
var $div = $('div');
function brFun() {
$div[($div.hasClass('br') ? 'remove' : 'add') + 'Class']('br');
};
setInterval(brFun, 2000);
});
Demo: Fiddle