setTimeout()不起作用

时间:2014-04-21 09:43:05

标签: javascript

我想每1秒钟计算下面文本框的数量。  我尝试过如下。但是这不起作用......我不知道我错在哪里。  而且我想在文本框值达到10后停止计数。  请给我任何解决方案......谢谢

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
var fun = function()
{

var count = $("#target :text").val();

$("#target :text").val(count++);

setTimeout(fun, 1000);

}

fun();
</script>

<div id="target">
<input type="text" value="0">
</div>

8 个答案:

答案 0 :(得分:5)

使用++count代替count++,您的代码问题在于您使用的是后期增量。

$("#target :text").val(++count);

DEMO

此外,我建议您使用document-ready处理程序。

修改

预增量示例

var count  = 0; //Suppose
$("#target :text").val(++count); 

相当于

var count  = 0; 
count = count + 1;
$("#target :text").val(count); //Will set value as 1

POST增量示例

var count  = 0; //Suppose
$("#target :text").val(count++); 

相当于

var count  = 0; 
$("#target :text").val(count); //Will set value as 0
count = count + 1;

答案 1 :(得分:1)

问题在于,val()为您提供了字符串

var fun = function() {
    var el = $("#target :text");
    var count = parseInt(el.val(), 10);
    el.val(count+1);
    setTimeout(fun, 1000); 
}

fun();

答案 2 :(得分:1)

你可以这样做,实际上是数秒而不是计数器:

var t = new Date(), a = setInterval(function() {
    $("#target>").filter(':input').val(function() {
        if ((c = (Date.now() - t.getTime()) / 1000) >= 10)
            clearInterval(a);

        return Math.round(c);
    });
}, 1000);

演示here

修改

因为我喜欢Coffeescript:

t = new Date()

a = setInterval ->
    $('#target>').filter(':input').val ->
        clearInterval a if (c = (Date.now() - t.getTime()) / 1000) >= 10

        Math.round c
, 1000

答案 3 :(得分:1)

大多数答案都是错误的,令人困惑,并且没有弄清楚这是什么问题。 您设置间隔循环的方式是完全正确的。

您错过的是count++将返回count然后再增加它。 因此,您始终将计数设置为0。首先需要增加count然后设置它。 你可以使用++count作为Satpal的提议。

我认为为var updatedTime = count + 1;创建一个临时变量然后将其设置为updatedTime更清晰。这样一来,它就会变得更加清晰,而且很难被像你这样的bug所困扰。功能方面,两种方法都是相同的。

答案 4 :(得分:1)

Keep it simple

function fun (){
 $("#target :input").val(function(){return +this.value + 1;});
 setTimeout(fun, 1000);
}

答案 5 :(得分:0)

演示:http://jsfiddle.net/39qVC/

var fun = function ()
    {
        var count = $("#target :text").val();
        if(count >= 10) {
            clearTimeout(loop);
        }
        else
        {
            $("#target :text").val(parseInt(count, 10) + 1);
        }
    }

    var loop;
    $(document).ready(function(){
        var count = $("#target :text").val();
        loop = setInterval(fun , 1000);
    });

答案 6 :(得分:0)

这些答案都没有考虑到setTimeout或setInterval不是实时操作。你的时间将会消失。不要使用柜台。

使用Date对象计算已用时间,显示经过的秒数,然后您可以使用setInterval更新视图。

答案 7 :(得分:-1)

尝试下面的代码工作..

 <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
 <script>
 function fun()
 {
   var count = $("#target :text").val();
   count= parseInt(count) +1;// We have to parse value in to the int or other datatype.
   $("#target :text").val(count);
 }
   setInterval('fun()', 100);
</script>
<div id="target">
<input type="text" value="0">
</div>

我们需要解析计数值,因为它是字符串格式。