Javascript setTimeout() run fade animation

Introduction

Use the setTimeout() function if you are doing some time consuming stuff.

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Calling a Function Repeatedly with setInterval() Method</title>
<style>
    img{//from   ww  w.j a v a 2  s. c om
        display: none;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
var myVar;
function showImage(){
    $("img").fadeIn(750).fadeOut(750);
    myVar = setTimeout(showImage, 2000);
}
function stopFunction(){
    clearTimeout(myVar); // stop the timer
}
$(document).ready(function(){
    showImage();
});
</script>
</head>
<body>
    <button onclick="stopFunction()">Stop Image Transition</button>
    <p>
        <img src="/examples/images/sky.jpg" alt="Cloudy Sky">
    </p>
</body>
</html>



PreviousNext

Related