Is there a way to call a function using setInterval without changing the HTML style?

<style>
        .a {
            width: 500px;
            height: 300px;
            background-color: #666;
        }

</style>

<body>
    <div class="a">

    </div>

    <script>
        function initiate() {

            setInterval( performRotation, 1000);
        }

        function performRotation() {
            document.getElementsByClassName('a')[0].style.transform = 'rotate(50deg)';
            document.getElementsByClassName('a')[0].style.transform = 'rotate(90deg)';
        }

        window.addEventListener('load', initiate);
    </script>
</body>

https://jsfiddle.net/TyTyT/frmawt85/

I encountered an issue where the transform style halts at 90deg and fails to proceed further.

My vision was to have the DIV tag oscillate between 50deg and 90deg.

Any suggestions on how to achieve this?

Answer №1

When it comes to rotation, the key is to keep updating the value of rotate in a timely manner. Below is an example for you to try:

<!DOCTYPE html>
<html lang="en>">
<head>
    <meta charset="UTF-8>">
    <title>Document</title>
    <style>
        .a {
            width: 100px;
            height: 100px;
            /* border: 1px solid red; */
            background-color: red;
            margin: 40px auto;
        }

</style>

</head>
<body>
    <div class="a">

    </div>

    <script>
    var rotate = 0;
        function startRotation() {
            let interval;
            // Remember to clear the interval
    if (interval) clearInterval(interval);
            interval = setInterval( rotateElement, 1000);
            
        }

        function rotateElement() {
        if (rotate > 360) rotate = 0;
        rotate += 50;
            document.getElementsByClassName('a')[0].style.transform = `rotate(${rotate}deg)`;
        }

        window.addEventListener('load', startRotation);
    </script>
</body>
</html>

Answer №2

Kindly review this proposed solution. It appears that you are attempting to oscillate the value and restart the loop similar to a pendulum. If this is the case, the provided solution may assist in achieving the desired outcome.

.as-console-wrapper {
  max-height: 20px !important;
}
.a {
  transition: all 1s ease;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <title>Document</title>
    <style>
        .a {
            width: 100px;
            height: 100px;
            /* border: 1px solid red; */
            background-color: red;
            margin: 40px auto;
        }

</style>

</head>
<body>
    <div class="a">

    </div>

    <script>
    let rotate = 60;
        function first() {
            let interval;
            // Remember to clear the interval
          if (interval) clearInterval(interval);
            interval = setInterval( a, 1000);
            
        }

        function a() {
            if(rotate === 60) rotate += 60;
            else rotate -= 60; 
            console.log(rotate);
            document.getElementsByClassName('a')[0].style.transform = `rotate(${rotate}deg)`;
        }

        window.addEventListener('load', first);
    </script>
</body>
</html>

Answer №3

By combining both CSS changes in a single function that is executed every second, the transitions happen quickly one after the other. But there's a simpler way to achieve this:

function rotate() {

    const degrees = ['rotate(50deg)', 'rotate(90deg)'];

    setInterval(() => {
        document.getElementsByClassName('box')[0].style.transform = degrees[0];
        degrees.reverse();
    }, 1000);
}

window.addEventListener('load', rotate);

Although this approach works, consider using CSS animations for a smoother effect like this:

<style>
    .box {
        width: 500px;
        height: 300px;
        background-color: #666;

        animation: spinAnimation 2s infinite;
    }

    @keyframes spinAnimation {
        0% {
            transform: rotate(50deg);
        }
        50% {
            transform: rotate(90deg);
        }
        100% {
            transform: rotate(50deg);
        }
    }
</style>

To learn more about CSS animations, visit:

https://developer.mozilla.org/en-US/docs/Web/CSS/animation

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

CSS - Inconsistencies in size rendering across Chrome and Safari

I'm a Computer Science freshman and I created a website a few weeks ago. Initially, I checked it only on Safari and everything looked fine. However, when I tried it on Google Chrome, the layout appeared completely different. How can I resolve this iss ...

Sending a JavaScript Array to PHP results in receiving Undefined or Disallowed Key Characters

I've been grappling with this problem for a few days now. I have an array in JavaScript that I need to send over to my PHP method. This is my PHP code: public function saveCampaignSendToMediaOwner() { $result = $this->input->post(); e ...

Jquery Validation Plugin - Specifically for validating numeric inputs in specific situations

I am currently working on implementing validation using jQuery Validate for a numeric value, but only when a specific radio button is checked. If the radio button is not checked, the field should be required and allow alphanumeric values to be entered. How ...

Text "movement/vibration" in screen when adjusting dimensions in Firefox for Mac

I am currently involved in a project centered around showcasing a variety of fonts to users for them to experiment with, allowing them to adjust size and spacing using sliders. While the functionality works seamlessly on Chrome and Safari, a peculiar issu ...

Rotating a rectangular sprite around a sphere in three.js while keeping a minimum distance

In a three.js environment, featuring a static camera, and a sphere positioned at 0,0,0, along with a rectangular sprite (such as a text label) of varying dimensions, I am seeking a 'threejs method' or formula to enable the rotation of the sprite ...

What is the best way to manage DOM modifications in a responsive design layout?

Developing a responsive website with only one breakpoint can be challenging, especially when restructuring the DOM to accommodate different screen sizes. It's important to consider not just CSS and media queries, but also how the elements are arranged ...

What is the best way to target a nested selector in CSS?

To ensure the entire cell is filled when a modal is present, the padding of the table should be zero. See image https://i.sstatic.net/Qq2T4.png How can I target the specific selector nested within the table under different classes and IDs? I've expe ...

AngularJS Issue [$injector:modulerr]

My AngularJS module, developed following these tutorials, is not working properly in conjunction with ASP.NET MVC. I have encountered an error [$injector:modulerr] and I am unsure of how to resolve it. (function () { var AAngScript = angular.module(&a ...

Another option instead of preloading images

Currently, I am in the process of creating a jQuery slideshow. After reviewing numerous tutorials on the subject, it appears that most recommend preloading images using code similar to the following: imageArray[imageNum++] = new imageItem(imageDir + "02. ...

Using AJAX to call a PHP function within a PHP script

I have successfully implemented an AJAX file that can execute content from a PHP file. However, my concern is how to specifically call a particular function within the PHP file if there are multiple functions present. Below is my current AJAX code: $(doc ...

Is there a way in Vue to switch between encrypted and unencrypted content in an input field?

I'm grappling with the challenge of creating an input field where the contents are initially hidden as 'ab****gh' and can be toggled to reveal as 'abcdefgh' upon a click. I've been experimenting with some code, but I'm st ...

MERN stack: HTML is currently processing while React is failing to compile

I can't seem to figure out why I'm not receiving an error message, but when trying to launch a react app with node, only the Html is being displayed. Am I overlooking something? I've attempted the <script type="text/babel" src=".. ...

What steps should I follow to convert the cookie values into a 'key: value' array?

I need to create a comprehensive list of cookies along with their values, retrieve the values, and then store them in a different location var cookieNames = ["Cookie1", "Cookie2", "Cookie3"]; function getCookie(cookieName) { let name = cookieName + "="; ...

Unsubscribe from the Event Listener in Node.js

In light of this inquiry (linked here), can the Listener be eliminated from within the callback function? To illustrate: let callback = function(stream) { if(condition) performAction(); else server.removeListener('connection', cal ...

A guide on making an expandable div with absolute positioning in Angular Material

I'm attempting to implement a collapsible div using angular-material that I want to be anchored to the bottom left corner, similar to the example shown in the image below. Do you think this is achievable? https://i.sstatic.net/ydmtc.jpg ...

Determine the precise x and y coordinates of a centered element using JQuery

How can I determine the exact left and top positions of an element? The parent container has text-align: center, causing potential confusion when there are multiple elements on the bottom row. For instance, the first one may have a position of 0px instea ...

Is there a way to interact with specific locations on an image by clicking in JavaScript?

https://i.stack.imgur.com/gTiMi.png This image shows a keypad with coordinates for each number. I am able to identify the coordinates, but I am struggling to click on a specific coordinate within the image using JavaScript. Can someone assist me in achiev ...

Prevent zooming on the entire webpage except for the images

I'm in the process of developing a basic PWA and am aiming to give it the appearance of a native mobile application, but I'm encountering obstacles with pinch-in functionality. In my layout.html file (utilizing Flask for the backend), I've ...

Guide on creating a Sequelize query to retrieve all tasks linked to a specific user_id

I'm currently developing my first to-do list application using node express ejs and sequelize with sqlite Below is my sqlite.js file which contains the database schemas: const Sequelize = require("sequelize"); const sequelize = new Sequelize({ dia ...

Audio in A-Frame does not function properly when in VR mode

My friend and I are collaborating on a small project involving a VR simulation that requires audio instructions. While everything functions smoothly in the web version and even on mobile devices, we encountered an issue when switching to VR mode on mobile ...