我如何让这个javascript每秒运行一次?

use*_*049 38 javascript ajax

对不起我是一个菜鸟我只是想知道我是如何让这个javascript每秒运行一次?

源代码:

<script type="text/javascript">
$(function() {
    //More Button
    $('.more').live("click",function()  {
        var ID = $(this).attr("id");
        if(ID) {
            $("#more"+ID).html('<img src="moreajax.gif" />');

            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: "lastmsg="+ ID, 
                cache: false,
                success: function(html){
                    $("ol#updates").prepend(html);
                    $("#more"+ID).remove();
                }
            });
        } else {
            $(".morebox").html('no posts to display');
        }

        return false;

    });
});

</script>
Run Code Online (Sandbox Code Playgroud)

Mik*_*wis 70

使用setInterval()每隔x毫秒运行一段代码.

您可以在所调用的函数中包装要运行的代码runFunction.

所以它会是:

var t=setInterval(runFunction,1000);
Run Code Online (Sandbox Code Playgroud)

要阻止它,你可以运行:

clearInterval(t);
Run Code Online (Sandbox Code Playgroud)

  • 或[setInterval()](http://www.w3schools.com/jsref/met_win_setinterval.asp) (5认同)
  • `setTimeout(runFunction,1000)`拜托.不要传递字符串.并且它不会每隔*秒执行代码*(至少有一些缺失). (2认同)
  • @hannunehg 为什么? (2认同)

Tow*_*own 7

用途setInterval:

$(function(){
setInterval(oneSecondFunction, 1000);
});

function oneSecondFunction() {
// stuff you want to do every second
}
Run Code Online (Sandbox Code Playgroud)

下面是文章上的区别setTimeoutsetInterval.两者都将提供您需要的功能,它们只需要不同的实现.


小智 6

您可以使用 setTimeout 运行一次函数/命令或使用 setInterval 以指定的时间间隔运行函数/命令。

var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);

//To abort the interval you can use this:
clearInterval(b);
Run Code Online (Sandbox Code Playgroud)