在for循环中使用setTimeout和一个整数 [英] Using setTimeout and an integer in a for loop

查看:115
本文介绍了在for循环中使用setTimeout和一个整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 play 的按钮。



我想用这段代码对该按钮进行倒数计时。但由于某种原因,我无法得到这个工作。

  var timeoutTime = 500,seconds = 5; 
var countdown = $(#play h4);
for(var i = seconds; i> 0; i--)
{
setTimeout(function(){
countdown.text(+ i);}, timeoutTime);
timeoutTime + = 1000;

$ / code>

我尝试了很多东西,我能得到的最好的只有一个而不是5 4 3 2 1.有了这个代码,我得到了一个0按钮。



有什么问题?

  for(var i = seconds; i> 0)解决方案

;函数(i){
setTimeout(function(){
countdown.text(+ i);},timeoutTime);
} )(一世);
timeoutTime + = 1000;





你的问题是我改变了,你总是用最后一个值因为你传给setTimeout的回调函数在循环完成后被调用。

经典的解决方案是使用闭包来保存另一个变量(这里同名) )具有期望的值。它的工作原理是每次迭代都有一个不同的函数(变量的作用域是全局作用域或声明的函数)。

I have a button with id play.

I want a countdown on that button with this code. But for some reason I can't get this to work.

var timeoutTime = 500, seconds = 5;
var countdown = $("#play h4");
for(var i = seconds; i>0; i--)
{
    setTimeout(function() {
    countdown.text("" + i); },timeoutTime);
    timeoutTime += 1000;
}

I tried a lot of things, the best I could get was just a 1 instead of 5 4 3 2 1. With this code I get a 0 on the button.

What's the problem ?

解决方案

Use this :

for(var i = seconds; i>0; i--) {
    (function(i){
      setTimeout(function() {
          countdown.text("" + i); }, timeoutTime);
    })(i);
    timeoutTime += 1000;
}

Your problem was that i changes and you were always calling with the last value of i, because the callback you pass to setTimeout is called after the loop finishes.

The classic solution is to use a closure to keep another variable (here with the same name i) having the desired value. It works because this is a different function for each iteration (the scope of a variable is either the global scope or the function where it is declared).

这篇关于在for循环中使用setTimeout和一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆