这个需求涉及使用jQuery创建一个可以无限循环执行的函数,直到用户点击停止按钮来中断循环。这在前端开发中常用于轮播、动画或定期更新数据的场景。
以下是完整的实现代码示例:
<!DOCTYPE html>
<html>
<head>
<title>无限循环示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#status {
margin-top: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<button id="startBtn">开始循环</button>
<button id="stopBtn">停止循环</button>
<div id="status">状态: 未启动</div>
<div id="counter">循环次数: 0</div>
<script>
$(document).ready(function() {
let intervalId = null;
let counter = 0;
// 循环执行的函数
function loopFunction() {
counter++;
$('#counter').text('循环次数: ' + counter);
console.log('循环执行中...', counter);
// 这里可以放置你需要循环执行的代码
// 例如:更新UI、获取数据等
}
// 开始按钮点击事件
$('#startBtn').click(function() {
if (intervalId === null) {
$('#status').text('状态: 运行中');
// 设置循环间隔为1秒(1000毫秒)
intervalId = setInterval(loopFunction, 1000);
console.log('循环已启动');
}
});
// 停止按钮点击事件
$('#stopBtn').click(function() {
if (intervalId !== null) {
clearInterval(intervalId);
intervalId = null;
$('#status').text('状态: 已停止');
console.log('循环已停止');
}
});
// 页面关闭时清理定时器
$(window).on('beforeunload', function() {
if (intervalId !== null) {
clearInterval(intervalId);
}
});
});
</script>
</body>
</html>
setInterval()
创建定时循环,clearInterval()
停止循环intervalId
变量跟踪定时器状态loopFunction()
是每次循环执行的核心函数问题1:循环不停止
intervalId
或错误地调用了clearInterval
intervalId
变量问题2:页面卡顿
问题3:内存泄漏
beforeunload
事件处理程序清理定时器这个实现方案可以根据具体需求进行调整,例如修改循环间隔时间或在循环函数中添加特定的业务逻辑。
没有搜到相关的文章