Javascript:给setTimeout的函数调用是什么? [英] Javascript: What does the function given to setTimeout get called with?

查看:195
本文介绍了Javascript:给setTimeout的函数调用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

  setTimeout(foo,600); 

我一直认为 foo 任何参数,例如:

  function foo(){/ * bars * /} 
  

function foo(a){alert(a); / * bars * /}

弹出显示-7的警报。这个数字代表什么?

解决方案

这是它计划运行它的时间差(以毫秒为单位)

  alert(setTimeout(function(a){alert(a)},2000) 

如果您及时清除第一个警报,您将看到下一个警报是-10到10如果你等待几秒钟,你会看到在等待减去2000的时间周围的东西。



setInterval也可以看到同样的事情。在Firebug中运行以下命令:

  setInterval(function(a){alert(a);},2000); 

尝试快速关闭警报,它将再次为0。

注意这是在Firefox Mac上,其中保持警报打开将停止处理Javascript,所以定时器不会执行,直到我关闭警报。上述测试的行为在其他浏览器


中可能会有所不同

I have code like this:

setTimeout(foo, 600);

I always thought that foo didn't take any arguments, e.g.:

function foo() { /* bars */ }

However, doing the following:

function foo(a) { alert(a); /* bars */ }

Popped up an alert displaying -7. What does this number represent?

解决方案

It is the time difference (in milliseconds) from when it was scheduled to run it and when it actually ran.

alert(setTimeout(function(a) { alert(a) }, 2000));

If you clear the first alert in time, you will see the next alert is somewhere -10 to 10. If you wait a few seconds, you will see something that is around the time you waited minus 2000.

The same thing can be seen for setInterval. Run the following in Firebug:

setInterval(function(a) { alert(a); }, 2000);

Try closing the alert quick, it will be around 0 again. Leave it open - it will give you a large value.

Note This is on Firefox Mac, where keeping an alert open will halt processing of Javascript, so the timer does not execute until I close the alert. The behavior of the tests above may be different in other browsers

这篇关于Javascript:给setTimeout的函数调用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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