社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Jquery

避免在setInterval jquery中等待时间

Max • 5 年前 • 1358 次点击  

我正在写剧本 li 内容显示在 input

我必须等待10秒,让代码在初始化后开始执行 button 点击。。。

如何避免这种行为?我只想剧本马上开始。

$("button").on("click", function() {
  var items = $(".menu li"), idx = 0;

  var timer = setInterval(function() {
    var currText = items.eq(idx).text()
    if (idx < items.length - 1) idx++;
    else idx = 0;
    
    
    $("#show").val(currText);
 
  }, 10000);
});
input {
  width: 40px;
  height: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button>show li in order every 10 seconds</button>

<input type=text id="show" />
<ul class="menu">

  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
</ul>
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53243
 
1358 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Roko C. Buljan
Reply   •   1 楼
Roko C. Buljan    5 年前

创建一个函数
别忘了使用 .one() 而不是 .on()

var items = $(".menu li"), $show = $('#show'), idx = 0, timer = null;

function doIt () {
  var currText = items.eq(idx).text()
  if (idx < items.length - 1) idx++;
  else clearInterval(timer);
  $show.val(currText);
  timer = setInterval(doIt, 1000);
}

$("button").one("click", doIt);
input {
  width: 40px;
  height: 40px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button>show li in order every 10 seconds</button>

<input type=text id="show" />
<ul class="menu">
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
</ul>