问题
I know that the difference would currently be negligible due to inaccurate browser timers, but for the sake of knowledge if nothing else: is there any browser that supports setInterval and setTimeout, but requires that they be passed an integer value as a delay?
Or, rephrased with examples, is this:
setInterval(animate,50/3);
as cross-browser compatible as this?
setInterval(animate,17);
回答1:
It is perfectly safe.
(As RobG points out, I haven't provide a reference to the DOM/JS bridge rules themselves and he urges caution. FWIW, I believe -- but have no reference to conclusively state -- that ToInteger
is part of the interface bridge. Here is a jsfiddle showing the timeout being passed as a string, a float, and an integral (same type as float in JS) which works fine in FF8 and IE9. Feedback welcome.)
This is because the DOM interface only accepts integers for the delay in setTimeout/setInterval
-- yup, these are defined in the DOM, not in ECMAScript. The delay value is appropriately converted to an integral value first (and in this aspect the [JS-internal] ToInteger
function is invoked which performs a truncation*).
However, the example numbers will actually yield slightly different results (although it might not be noticable) :-)
This is because, 50/3
(16.66andsomemore
-> 16
) and 17
specify different timeouts.
Happy coding.
*ToInteger
is defined as sign(number) * floor(abs(number))
, excluding special cases. See Section 9.4 of the 5th Edition ECMAScript specification.
回答2:
Javascript makes no real distinction between floating point numbers and integers, and are the same data type under the hood. 1
and 1.0
are bit for bit identical in memory.
Therefore yes, you can pass a fractional value without any real issues. It's perfectly valid JavaScript. And even if it did require an integer, it's more likely it would simply and silently round it down for you.
But don't expect it to be accurate! A time of 0.1
, 1
or even 4.87
will all probably fire at very close to the same time due to the low granularity of the callback scheduling.
回答3:
I would imagine that the second parameter would be evaluated as an expression and as long as it returns a number it will work. It seems to work in chrome. Just make sure you don't divide by zero!
回答4:
These functions expect milliseconds. I doubt you could expect any accuracy greater than 10ms, and browsers enforce timer restrictions.
Firefox doesn't mind decimal values. You can test in any other browsers you're curious about.
来源:https://stackoverflow.com/questions/8468790/is-it-safe-to-pass-setinterval-or-settimeout-a-fractional-delay