Utilizing CSS animation triggered by a timer to produce a pulsating heartbeat effect

Here's a unique way to achieve a heartbeat effect on a spinning circle. The goal is to have the circle double in size every second and then shrink back to its original size, resembling a heartbeat. To achieve this, a JavaScript timer is set up to remove and immediately add a class that triggers the growth effect. However, the desired "heartbeat" effect only occurs once.

Additionally, the aim is to have the circle spin at a constant speed without slowing down at the end or starting slowly. Currently, the animation has a noticeable slowdown towards the end.

// set timeout
let tid = setTimeout(mycode, 1000);
function mycode() {
  // do some stuff...
  let ic = document.getElementById('inner-circle')
  ic.classList.remove('heartbeat')
  ic.classList.add('heartbeat')
  tid = setTimeout(mycode, 1000); // repeat myself
}
function abortTimer() { // to be called when you want to stop the timer
  clearTimeout(tid);
}
#spinning-circle {
    animation-name: spinning-circle;
    animation-duration: 10s;
    animation-iteration-count: infinite;
    width: 40px;
    height: 40px;
}

.heartbeat {
    width: 100%;
    height: 100%;
    animation-name: heartbeat;
    animation-duration: 0.15s;
    animation-iteration-count: 2;
    animation-direction: alternate;
    animation-fill-mode: both;
}

#inner-circle img {
    width: 100%;
    height: auto;
}

@-webkit-keyframes heartbeat {
    100% {
        transform: scale(2,2);
        -webkit-transform: scale(2,2);
    }
}

@-webkit-keyframes spinning-circle {
    0% {
        -webkit-transform: rotate(0deg);
        transform: rotate(0deg);
    }
    100% {
        -webkit-transform: rotate(360deg);
        transform: rotate(360deg);
    }
}
<div id="spinning-circle">
    <div id='inner-circle'>
        <img src="https://i.sstatic.net/WbNlQ.jpg">
    </div>
</div>

Answer №1

Consider using setInterval() and clearInterval() in place of setTimeout(). Also, eliminate the setTimeout() within the mycode() function.

// set timeout
let tid = setInterval(mycode, 1000);
function mycode() {
  // do some stuff...
  let ic = document.getElementById('inner-circle')
  ic.classList.remove('heartbeat')
  ic.classList.add('heartbeat')
}
function abortTimer() { // to be called when you want to stop the timer
  clearInterval(tid);
}

To adjust the animation speed, include

animation-timing-function: linear;
in
.heartbeat {} and #spinning-circle {}

Answer №2

Who needs javascript when you can do this without it:

#spinning-circle {
    margin-top: 40px;
    margin-left: 40px;
    animation: spinning-circle linear 10s infinite;
    width: 40px;
    height: 40px;
    overflow: visible;
}

#inner-circle {
    animation: heartbeat 1s infinite;
}

#inner-circle img {
    width: 100%;
    height: auto;
}

@keyframes heartbeat {
    0% {
        transform: scale(1);
    }

    25% {
        transform: scale(2);
    }
    
    50% {
        transform: scale(1);
    }
    
    100% {
        transform: scale(1);
    }
}

@keyframes spinning-circle {
    0% {
        transform: rotate(0turn);
    }
    100% {
        transform: rotate(-1turn);
    }
}
<div id="spinning-circle">
    <div id='inner-circle'>
        <img src="https://i.sstatic.net/WbNlQ.jpg">
    </div>
</div>

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

Order a portion of a JSON array according to another part of the same array

Having a json array that needs sorting in JavaScript. The EventName field should match the respective Age fields like 01-10 Days and 10-20 Days. [ {Age: "01-10 Days", EventName: "Invoice AP Review", Value: 1, ActiveInvoices: []} ,{Age: "01-10 Days", Even ...

Proper method for verifying line-clamp in a Vue component

I came across a question that aligns perfectly with my current task - determining if text is truncated or not. The query can be found here: How can I check whether line-clamp is enabled?. It seems like my approach may not be accurate, so any guidance on ho ...

Having trouble with gsap.reverse() not functioning properly when using onMouseLeave event in React

I've been incorporating simple gsap animations into my React application. I have successfully triggered an animation.play() function on onMouseEnter, but for some reason, the animation.reverse() function is not functioning as expected. Here's ho ...

What is the method for dividing a string (object) to 'preserve' in a fresh piece?

Upon receiving the following JSON file: var data = [ { "id":"1", "yMonth":"201901", }, { "id":"2", "yMonth":"201902", }, { "id":"3", "yMonth":"201802", }, { "id":"4 ...

Is there an alternative if statement with 3 or more conditions?

I've been attempting to solve this issue for quite some time now, but I just can't seem to pinpoint what exactly I'm doing incorrectly. The first two conditions appear to be functioning properly, but the third one is failing to execute as ex ...

What is the reason behind the lag caused by setTimeout() in my application, while RxJS timer().subscribe(...) does not have the same

I am currently working on a component that "lazy loads" some comments every 100ms. However, I noticed that when I use setTimeout for this task, the performance of my application suffers significantly. Here is a snippet from the component: <div *ngFor ...

Setting up a secure Node.JS HTTPS server on Cloud9 IDE

Wondering if it's possible to set up a Node.js https server in the cloud9 IDE? Check out this example of a basic https server setup in Node.js. var https = require('https'); var fs = require('fs'); var app = require('./app& ...

Tips for updating nested data in mongoose with 2 unique identifiers?

Is there anyone out there with experience in making a Node push function work on nested objects beyond just one level? I'm looking to delve deeper into a second id within the DB model. // Functional code for updating a user at one level with one id ...

The styles order definition in the Material-UI production build may vary from that in development

When using material-ui, an issue arises in the production build where the generated styles differ from those in development. The order of the material-ui styles in production does not match the order in development. In DEV, the material-ui styles are defi ...

Creating a dynamic grid design with images using the <ul><li></li></ul> HTML tags

Trying to create a responsive grid of images that adapts to changes in browser size. Is there a way to achieve this using a list? Ideally, I want the images to be evenly spaced in rows. For example, if there are three rows of four images on top and one r ...

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

Is it possible to create a TypeScript generic type that transforms a Record into a type by utilizing the `as const` keyword?

Imagine this scenario: I define const foo = { myKey: 'myValue' } as const Now, when I ask for typeof foo, I get { readonly myKey: 'myValue' } If I have a type MyType = Record<string, string>, and I want to create a modifier (let ...

The AngularJS routing template fails to load

I am currently working on the app.js file: 'use strict'; var app = angular.module('app', [ 'auth0', 'angular-storage', 'angular-jwt', 'ui.router', 'Environment', ...

Angular 2's innovative approach to implementing a sticky footer concept

Is there a way to make my footer sticky without being fixed? I attempted using the CSS negative margin trick, but it did not work as expected. In the provided Plunker code, I tried to replicate the issue in my Angular 2 app. The goal is for the footer to s ...

How can the marionette controller object generate unique prototype methods that are dynamic?

Currently, I am working with Marionette to develop an application with multiple pages. The process of instantiating views and displaying them through the appRegion in each controller/router method feels repetitive. My goal is to streamline this process by ...

Having issues with getting Bootstrap to function properly in my create-react-app

I've been attempting to use traditional Bootstrap instead of react-bootstrap to render my React component, but I can't seem to get it right. I've installed Bootstrap via npm and included the CDN links and scripts as well. Despite trying vari ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...