What is the reason it is only functioning one time?

This div should always toggle without utilizing the 'toggle' method.

$(document).ready(function(){
      function brFun() {
        $('div').addClass('br');
        setTimeout('$(\'div\').removeClass(\'br\')', 2000)
      };
      setInterval(brFun, 2000);
    });

Answer №1

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The setInterval function with a time interval set to 1ms does not appear to function exactly as a 1ms delay

I'm attempting to measure the duration of a file download using an HTTPRequest as seen below: function getFile() { 'use strict'; var url = "data.bin"; var rawFile = new XMLHttpRequest(); var timer_var = setInterval( theTimer ...

Issues with redirection to registration page in PHP Slim framework

When I access localhost/path/home, it takes me to the homepage where I can either login or signup. Clicking on either option should redirect me to localhost/path/login or localhost/path/signup respectively for the login or signup page. However, there seem ...

Reliably analyzing text to generate unprocessed HTML content

My input text in a textarea is structured like this: This is some sample text./r/n /r/n This is some more sample text. I want to format it for display as follows: <p>Here's some text.</p> <p>Here's some more text.</p> ...

Adjust sliders when buttons are clicked

Looking for advice on how to implement jQuery sliders when clicking buttons on my webpage. Additionally, I would like the slider to switch from slider1 to slider2 upon the second button click. I attempted using ajax but encountered difficulties. Thank yo ...

Prisma generate: encountering issues resolving the dependency tree with Prisma, Postgresql, and NextJS integration

Every time I execute prisma generate, the following error is displayed: Prisma schema loaded from prisma/schema.prisma npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

What is the best way to incorporate this into a Vue project?

I am in the process of transitioning my code to Vue.js, so I am relatively new to Vue. In the screenshot provided (linked below), you can see that there are 4 columns inside a div with the class name columns. I attempted to use the index, like v-if='i ...

The echo function is repeating something that is not text

I have set up a basic bottle server using Python: from bottle import route, run, static_file @route('/') def home(): return static_file("home.html", root='.') @route("/<fileName>") def respond(fileName): return static_f ...

Guide on validating an input field with an array type name using the jquery.validate.min.js plugin

I am dealing with input tag fields that each have a name attribute within an array. For example: <div class="form-group"> <label class="col-sm-2 control-label"> <span style="color: red;">*</span> Title</label ...

Using Vue with Firebase to fetch a specific range of data starting from a particular record and ending at the

I am looking to retrieve all records from a certain record to the very last one in my database. ref.orderByChild("date").equalTo("19/11/2020 @ 19:50:29").on("child_added", (snapshot) => { console.log(snapshot.va ...

Having trouble with your custom accordion content in React JS not sliding open?

Check out my progress so far with the fully functioning view here This is the structure of the Accordion component: const Accordion = ({ data }) => { return ( <div className={"wrapper"}> <ul className={"accordionList ...

Emails are not responsive to media queries

I've experimented with multiple media queries in an attempt to make this work on both iPhone (landscape/portrait) and desktop, but I'm struggling to achieve the desired outcome on both simultaneously. While some of my classes are functioning cor ...

A layout featuring two columns that have heights which are fixed to the bottom of the footer

I've designed a simple layout featuring 2 columns and a footer that adjusts based on the height of the longer column. <div id="holder"> <nav class="navbar navbar-default navbar-fixed-top"></nav> <div class="container"> ...

The user ID variable has not been declared

After successfully retrieving the username from a link, I am facing difficulty in getting the user id back. While displaying the username works perfectly fine, I encounter an issue with fetching the userId when trying to populate the thumbnail - it shows " ...

What is the best way to adjust the size of a Div slideshow using

I need help with creating a slideshow that covers my webpage width 100% and height 500px. The image resolution is 1200*575. Can someone assist me with this? CSS #slide{ width : 100%; height: 500px; } HTML <!DOCTYPE html> <html> ...

The specified variable is not present within the for loop

This script dynamically generates table rows for each client, populating each row with specific values such as name, IP address, operating system, country, and time. These values are stored in an object or dictionary named clientel. The setup of the progr ...

Combining Objects in an Array using JavaScript

Here is an array example: let array = [ { yearBirth : 1995, name : 'daniel', }, { yearBirth : 1995, name : 'avi', }, { yearBirth : 1993, name : 'john', }, { yearBirth : 1993, n ...

Removing data from database with ajax

I am encountering an issue with deleting records from my database using ajax and jquery. When I click the button, nothing happens. Here is the relevant css code: <button class='delete_p' id_p='<?php echo $post_id; ?>'>x< ...

Tips for resizing a Textbox by dragging in asp.net?

Is there a way to dynamically adjust the size of a Textbox by dragging it in an ASP.NET application during run-time? ...

Is JavaScript the go-to solution for rearranging a list of objects?

I have come across a data structure related question that I believe would be best addressed in this forum. Recently, I have been encountering the following issue frequently. I receive data from a service in the following format. It consists of an array of ...

How to move content without affecting the background of the `<body>` using scrolling

Can I achieve a glass morphism effect on my page without moving the background of the body? I only want to move the .container. Is this feasible? I attempted using background-attachment: fixed, but it did not work for me. Here is the code snippet I have be ...