Javascript setInterval()不工作
我试图以“1秒”的Javascript setInterval()不工作,javascript,jquery,function,setinterval,Javascript,Jquery,Function,Setinterval,我试图以“1秒”的setInterval()运行函数,但它有点问题。我已经做了所示的一切,但它不工作 这是我的密码: <script> function test(db_time) { var c_db_time= db_time/1000; var current_time = new Date().getTime()/1000; return Math.round(current_time - c_db_time); }
setInterval()
运行函数,但它有点问题。我已经做了所示的一切,但它不工作
这是我的密码:
<script>
function test(db_time)
{
var c_db_time= db_time/1000;
var current_time = new Date().getTime()/1000;
return Math.round(current_time - c_db_time);
}
$(".elapsed_time").each(function() {
var time_r = $(this).data('time_raw');
var inter = $(this).html(time_ago(time_r));//parameter to function
setInterval(inter,1000)
});
</script>
在函数的第一个参数中,应该传递一个函数或匿名函数,如
setInterval(function(){
console.log("1s delayed")
},1000);
如前所述,第一个参数应该是函数:
var self = $(this);
var inter = function() {
self.html(time_ago(time_r));
}
setInterval(inter, 1000);
请看这里:
什么是
inter
?函数?你能在var inter=$(this.html)行中发布你得到的吗
@Satpal其variablesetInterval仅接受函数Inter不是setInterval所期望的函数。$(this).html(time_ago(time_r));它返回的是错误的,我认为这不会像你期望的那样起作用。当函数运行时,此
是否会引用窗口?我不确定,因为您定义的函数超出了设置间隔。但是现在好多了,谢谢@Bommox,我已经编辑了你的答案。如果您觉得我的编辑不正确,请随时回滚。无论您在何处定义函数,变量this
将始终引用调用函数上下文(可由调用方更改)您必须考虑的另一件事是,time\r
变量可能需要重新读取,具体取决于它的使用方式。OK,但现在我遇到了一个新错误Uncaught TypeError:无法读取未定义的属性“createDocumentFragment”
var self = this;
setInterval(function(){
$(self).html(time_ago(time_r));
},1000);
var self = $(this);
var inter = function() {
self.html(time_ago(time_r));
}
setInterval(inter, 1000);
window.setTimeout( function() { /*your code which you want to execute after fixed interval, it can function name or lines of code*/}, /*fixedInterval*/);
window.setTimeout( function() { alert("Hello World!"); }, 5000); // it will execute after 5 seconds