最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass ID of setInterval() to anonymous funtion - Stack Overflow

programmeradmin2浏览0评论

I'm looking to pass the handler of setInterval() to the internal function.

For example:

var id = setInterval(myfunction, "100000");

I'm looking to pass id to myfunction

I tried

setInterval(myfunciton(e), "10000");

but it didn't pass the variable.

Any ideas?

I'm looking to pass the handler of setInterval() to the internal function.

For example:

var id = setInterval(myfunction, "100000");

I'm looking to pass id to myfunction

I tried

setInterval(myfunciton(e), "10000");

but it didn't pass the variable.

Any ideas?

Share Improve this question edited Aug 10, 2015 at 20:03 Hannes Johansson 1,8022 gold badges16 silver badges28 bronze badges asked Aug 10, 2015 at 19:46 axwegeaxwege 8611 bronze badges 1
  • Unless I misunderstood you, you can't pass a parameter that isn't even defined yet... – Maria Ines Parnisari Commented Aug 10, 2015 at 19:48
Add a ment  | 

2 Answers 2

Reset to default 12

The id doesn't exist when you call setInterval, but it does exist by the time that the callback is called.

You would need to wrap the call in a function that uses the id in a call:

var id = setInterval(function(){
  myfunction(id);
}, 10000);

If you include the variable in the callback as it's passed in to setInterval, the callback is immediately executing with that argument.

What you need to do is create a closure:

setInterval(function() {
  myFunction(e);
}, 10000);

Also, the interval should be an integer, not a string.

发布评论

评论列表(0)

  1. 暂无评论