JQuery - how to stop a function?
I have this code
<script type="text/javascript">
function test(counter) {
if(counter==4)
{
co开发者_开发知识库unter=0;
}
if(counter==0)
{
//various stuff
}
counter = counter + 1;
setTimeout(function () { test(counter); }, 7000);
}
$(document).ready(function () {
test(0);
});
</script>
So when the page loads the test(0)
function is running.
But i have this link <a onclick="test(1)" rel="2" href="#">
that calls the same function again, having as a result to have the same function running twice.
Is there a way to stop the function that is already running and then start the new one??
Save the result of setTimeout()
, and use it with clearTimeout()
.
function test(counter) {
if(counter==4)
{
counter=0;
}
if(counter==0)
{
//various stuff
}
counter = counter + 1;
var quit;
//decide whether to continue
if(!quit)setTimeout(function () { test(counter); }, 7000);
}
精彩评论