Creating animation using the setTimeout() method
The setTimeout() method can be used to call the animation function once after the given time. We can use it with an event and make it call the callback function every time the event occurs.
Syntax:
setTimeout(callback_function, delay_time);
Example: The below example implements the setTimeout() method to create a JavaScript animation.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content=" width = device -width, initial-scale = 1 .0"> < title >JavaScript - Animations</ title > < style > .animate { font-size: 25px; color: green; font-weight: 600; } </ style > </ head > < body > < center > < h1 >w3wiki</ h1 > < p id = "para" > Hover on this text to see the animation after 100 milliseconds. </ p > </ center > < script > const myPara = document. getElementById('para'); // Function to add animation function animatePara() { myPara.classList.add('animate'); } // Function to remove animation function removeAnimation() { myPara.classList.remove('animate'); } // Attaching functions with events // to add and remove animation myPara.addEventListener('mouseover', () => { setTimeout(animatePara, 100); }) myPara.addEventListener('mouseout', () => { setTimeout(removeAnimation, 100); }) </ script > </ body > </ html > |
Output:
JavaScript Animations
JavaScript is a very powerful scripting language. We can create animations in JavaScript using some CSS properties on the DOM elements. In this article, we will create some animations using JavaScript.
We can use the following methods to create animations using JavaScript:
Table of Content
- Creating animation using the setTimeout() method
- Creating animation using the setInterval() method
- Creating animation by using style property