在jQuery中,如何在不知道ID的情况下清除setting
在这篇文章中,我们将学习如何在不知道ID的情况下使用jQuery清除setInterval。首先,让我们简单地了解一下setInterval。这个方法是用来在一个特定的时间段内执行任何特定的函数或一些代码部分,这样我们就不必重复使用。当我们使用setInterval时,我们也必须使用clear interval方法,否则,setInterval将运行它的代码直到内存耗尽。
语法:
var ID = setInterval(function, <delay>);
当我们使用上层语法时,ID会返回一个整数值,这个整数值被称为setInterval的ID,这个值将被进一步用于清除setInterval。现在我们来看看两个例子,在这两个例子中,我们将使用ID清除setInterval,而不知道setInterval的ID,这就是本文的主要目的。
方法:当我们使用setinterval方法时,它自动生成了一个id,由于我们不知道它是什么,所以我们将使用一般的循环方法来清除区间,我们将运行一个从0到某个长数的循环,这样每个包含在这之间的区间将被清除。见下面的例子2。
例子1:在这个例子中,我们将使用setInterval方法来打印计数,我们将使用ID来清除区间。
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js"
integrity=
"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
</head>
<style>
#count{
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
</style>
<body>
<div id="count">
<h1 style="color: green;">GeeksforGeeks</h1>
</div>
</body>
<script>
(document).ready(function () {
var count = 0;
var id = setInterval(function () {
count++;
('#count').append(count + '<br>');
// clearing the interval
if(count == 5) {
clearInterval(id);
}
}, 500);
});
</script>
</html>
输出:
例2:在这个例子中,我们不会使用ID来清除区间,我们将使用清除区间,并通过区间的所有可能的ID进行循环,让我们看看这个例子以更好地理解。
<!DOCTYPE html>
<html lang="en">
<head>
<script src=
"https://code.jquery.com/jquery-3.3.1.min.js"
integrity=
"sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
</head>
<style>
#count {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
</style>
<body>
<div id="count">
<h1 style="color: green;">GeeksforGeeks</h1>
<button id="clear">ClearIntervals</button>
</div>
</body>
<script>
(document).ready(function () {
var count = 0;
var id = setInterval(function () {
count++;
('#count').append(count + '<br>');
}, 500);
$('#clear').click(function () {
for (var i = 1; i < 99999; i++)
clearInterval(i);
});
});
</script>
</html>