Use sample code for setInterval and clearInterval

  • 2020-03-30 01:33:58
  • OfStack

SetInterval is a useful js function that can be used to perform certain functions repeatedly. With this, we can achieve some interesting functions, such as:

Without refreshing the page, "real time" gets greetings from other members and displays something like that

Here's a sample code :(with some jquery methods)


<html>
<head>
<title>jquery  operation  Select</title>
<script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
<script type="text/javascript">
var i=1;
var _interval;
function showTime()
{
    var today = new Date();
    $("#msg").html(today.toLocaleString() + ",i=" + i);    
    i++;
    if (i>10)
    {
        clearInterval(_interval);
    }
}
$(document).ready(function(){    
    $("#btnStart").click(function(){
        showTime();
        _interval = setInterval("showTime()", 1000);
    })
    $("#btnStop").click(function(){                
        clearInterval(_interval);
        i=0;
    })
})
</script>
</head>
<body>
<label id="msg"></label> 
<button id="btnStart"> Start time </button> 
<button id="btnStop"> Stop the clock </button>
<script type="text/javascript"></script>
</body>
</html>


Related articles: