简体   繁体   中英

How make make a function repeat itself in jquery?

Let's say for example I want to make a function that makes a div fadeOut & fadeIn and repeat itself every 10 seconds. In jQuery. This is my current code.

window.setInterval(function(){
    $("leftEye").fadeOut("slow");
}, 5000);

CSS animation would seem more appropriate in this case - not least of all because it's hardware accelerated. You can create keyframes, then set them to animate over the period of 5 seconds, repeating infinitely.

 @keyframes fade { 0% { opacity: 1; } 50% { opacity: 0; } 100% { opacity: 1; } } .inifinte-fader { opacity: 1; animation: fade 5s infinite; } 
 <div class="inifinte-fader">Foo bar fizz buzz</div> 

If you want to use your approach with jQuery, you can just use fadeToggle instead of fadeOut .

// toggle the fade effect for #leftEye every 10 seconds
window.setInterval(function(){
   $("leftEye").fadeToggle("slow");
}, 10000); // 10000 milliseconds

This will make sure to appropriately toggle the fade effect every ~10s.

An arguably better approach would be to use CSS, as demonstrated by Rory McCrossan , especially instead of using jQuery for animation.

The reason is that the browser's rendering engine can usually perform the animations more efficiently using CSS (it can optimize things ahead of time) whereas animating using JavaScript sometimes cannot be optimized ahead of time. It's also easier and more expressive to write animation logic using CSS compared to using JS to manually perform various calculations such as transitioning the height or opacity over time.

Now, using jQuery for this animation is actually even more expressive than CSS (since its 1 line of code) but if performance is important using CSS definitely beats jQuery.

Its important to note however that well-optimized JavaScript (not jQuery) is often just as fast if not faster than CSS animations.

Here's a good article comparing animation using CSS vs JS and jQuery

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM