admin管理员组

文章数量:1356413

For reasons beyond me, I'm looking for a way to create a setInterval with a specific ID.

For example:

when you create a setInterval and assign it to a variable like so:

var myInterval = setInterval(function(){..},100);

myInterval is actually equal to a number.

so when you clear the interval you could either go clearInterval(myInterval), or use the number it is equal to.

myIntertval === 9;
clearInterval(9);

How can i make the myInterval === 20. and thus give my setInterval an ID of 20.

Is it even possible? Or am I simply being silly and should do everything the right way.

For reasons beyond me, I'm looking for a way to create a setInterval with a specific ID.

For example:

when you create a setInterval and assign it to a variable like so:

var myInterval = setInterval(function(){..},100);

myInterval is actually equal to a number.

so when you clear the interval you could either go clearInterval(myInterval), or use the number it is equal to.

myIntertval === 9;
clearInterval(9);

How can i make the myInterval === 20. and thus give my setInterval an ID of 20.

Is it even possible? Or am I simply being silly and should do everything the right way.

Share Improve this question asked Jul 4, 2014 at 7:55 Dustin SilkDustin Silk 4,6207 gold badges36 silver badges50 bronze badges 3
  • Agree with @hindmost, what is your need for having an interval with a specific number? – David Atchley Commented Jul 4, 2014 at 7:59
  • I had a bug where my setInterval was getting created a few times. So instead of debugging it i went for a quick solution of looping from 0 - its ID to remove it. Which i pletely regret now. – Dustin Silk Commented Jul 4, 2014 at 8:00
  • @Dustin Silk Do you create multiple intervals? – hindmost Commented Jul 4, 2014 at 8:02
Add a ment  | 

2 Answers 2

Reset to default 6

Is it even possible? Or am I simply being silly and should do everything the right way.

You should do it in the proper way (embrace refactoring!). Said this, you can fix it by "mapping" any ID to another value, just storing it in an object:

var myIntervals={};
myIntervals[0]=setInterval(function(){..},100);
myIntervals[20]=setInterval(function(){..},100);
myIntervals["hello"]=setInterval(function(){..},100);

Then you will have stored something like:

{ 0: <ID_first interval>,
  20: <ID_another_interval>,
  hello: <<ID_another_interval_more>
}

and then you can do:

clearInterval(myIntervals[requiredId]);

The id returned by 'setInterval' is unique, so there is no need for another unique identifier. In Theory, you could create a map, which maps your desired id to the one returned by setInterval and use this id for your internal code. But at the point where you would like to clear the interval, you have to use the original one. I would be interested in use case where this makes sense.

本文标签: javascriptsetInterval with specific ID numberStack Overflow