I am trying to write a Windows app. I am curious to know what happens when you pass WinJS.Promise.Timeout() undefined value rather than a numerical milliseconds value. Will it be equivalent to passing the function a value of 0, or the behavior is unpredictable?
According to the code the setImmidiate function is called when this value is not specified. This means the promise is fulfilled when the current task is completed.
When you pass 0 a JavaScript setTimeout function is used internally. This function is limited to 250 calls per second on some systems. When passing 'undefined' to WinJS.Promise.Timeout() it doesn't use a setTimeOut call. So it could be a bit faster in some cases.
You can find more info on the setImmidate function on MSDN.
As Sorskoot explains, the code makes it clear that setImmediate is called if the interval is zero or undefined. The docs (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/br229729.aspx) state this clearly:
timeout
Type: Number
The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called.
It's really just saying that a zero or undefined timeout should just yield the UI thread and then complete.
Related
timer = window.setTimeout(function () {
//do something
window.setTimeout(arguments.callee, 1000);
}, 1000);
the result is that these codes work well.
but why doesn't it cause the error below?
Maximum Call Stack Size Exceeded
when debugging it, find the variable scope don't include the scope of previous executed "setTimeout function"
Who can explain this?
with documentation preferably.
setTimeout is asynchronous (it returns before executing the callback), and the callback will be executed on a new, empty stack frame. That's the whole purpose. It will never overflow the stack.
It is not a recursive call, for which scope (in case of a non-tail-call-optimized function) would need to be retained. But that would also mean that the function became blocking, which is not what you want.
This is because the Timeout callbacks are not stored in the stack as you are assuming: there are in a queue, waiting to be executed in its own stack. And in your code the queue is filled when the previous execution is completed, so the queue is not growing.
UPDATE: You can check the specs here, but I'm copying the text:
The setTimeout() method must run the following steps:
Let handle be a user-agent-defined integer that is greater than zero
that will identify the timeout to be set by this call.
Add an entry to the list of active timeouts for handle.
Get the timed task handle in the list of active timeouts, and let
task be the result.
Get the timeout, and let timeout be the result.
If the currently running task is a task that was created by the
setTimeout() method, and timeout is less than 4, then increase
timeout to 4.
Return handle, and then continue running this algorithm
asynchronously.
If the method context is a Window object, wait until the Document
associated with the method context has been fully active for a
further timeout milliseconds (not necessarily consecutively).
Otherwise, if the method context is a WorkerUtils object, wait until
timeout milliseconds have passed with the worker not suspended (not
necessarily consecutively).
Otherwise, act as described in the specification that defines that
the WindowTimers interface is implemented by some other object.
Wait until any invocations of this algorithm started before this one
whose timeout is equal to or less than this one's have completed.
Optionally, wait a further user-agent defined length of time.
I created a var for a setInterval so I can stop it with clearInterval as such:
var repeat = setInterval(sayHello, 2000);
function sayHello() {
alert("Hello");
}
and here is the clearInterval:
clearInterval(repeat)
Now, in Firefox, once I ran this bit, if I want to know the value of "repeat", it returns the amount of time the interval ran. However, in Chrome, no matter how many times it ran, it always returns 1. Unless, I do the entire procedure over, it then return 2. It basically increments the instances as opposed to interval occurrences.
Anyone able to shed some light on this, how it works, and why...greatly appreciated!
All that is guaranteed is that setInterval will return a handle which can then be used by clearInterval. Other than that it is entirely up to the browser what that handle is and how it is used. Even if it seems to provide some information in one particular browser, that should not be relied on in any way as it will be subject to change.
To quote MDN:
The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to WindowOrWorkerGlobalScope.clearInterval() to cancel the timeout.
Don't expect it, or rely on it, to be anything else.
While reading source code, I saw a line
console.log(setTimeout("1"))
and this code has return a random number.
I don't know why. Please help me.
As per MDN,
The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setTimeout(); this value can be passed to Window.clearTimeout() to cancel the timeout.
So when you do = setTimeout(), you are not getting value of something that you have passed, but it a system generated identifier.
setTimeout registers an event in event heap after specified delay. If delay is not mentioned, it assumes as 0 but note, setTimeout(notify, 0) is not same as notify().
Also setTimeout expects a function as first parameter. When it receives a string, it assumes, you are passing function call as string and compiler tries to evaluate it using eval. So your setTimeout("1") will become eval("1") which will return "1" and hence you do not get error.
function notify(){
console.log('ta-da!!!');
}
var a = 10;
setTimeout("notify()",0)
// sample for eval
console.log(setTimeout("a"))
// This should throw error as `b` is not declared
console.log(setTimeout("b"))
I'm currently using a loop that repeats itself every few milliseconds in my program. In this loop, it checks for a certain input, and if received, cancels another timeout. Essentially:
if (inputreceived && secondTimerRunning)
{
timerID2.clearTimeout();
secondTimerRunning = false;
}
However, those lines cause my loop to terminate. From what I can tell, it's because I am trying to clear a Timeout that doesn't exist. Is there a way to prevent this, or am I using Timeouts wrong?
The syntax for clearTimeout() is;
clearTimeout(timerID2);
It is a function which accepts the ID returned by setTimeout(); i.e. you don't call it on the ID returned.
clearTimeout will not error if the value you pass to it is not a valid ID.
For more info, see the documentation for clearTimeout() on MDC.
Use clearTimeout(timerID2) instead, timeouts are represented by a number identifier and clearTimeout is a global function that can be called directly.
So I know that there are differences between setTimeout and setInterval, but consider these two code examples:
function myFunction(){
setTimeout('myFunction();', 100);
doSomething();
}
setTimeout('myFunction();', 100);
and
function myFunction(){
doSomething();
}
setInterval('myFunction();', 100);
Note that in the first example I call setTimeout at the begining of the function and then I doSomething. Therefore there is no extra delay from doSomething(). Does that mean that those two examples do exactly the same? Or is there even more subtle difference?
They're functionally about the same, but there are differences. One difference is in how browsers handle it if doSomething takes longer than the interval. With setInterval, at least some browsers will just skip the next interval if doSomething is still running. So if you use 100ms as you have, and doSomething takes 110 ms to run, the next run won't happen until 90ms later (of course, all of these times are approximate).
Another difference is that with the setTimeout, you'll get a new handle every time, whereas with setInterval you get one handle.
Another difference with your examples as given is that in the setTimeout example, you're firing up a JavaScript parser/compiler every time, whereas with setInterval you're only firing up the parser/compiler once. But this difference shouldn't matter, because you shouldn't be doing that at all — see below.
But subtleties aside, what you have there is functionally the same.
Side note: It's not best practice to pass strings into either setTimeout or setInterval. Instead, pass in a function reference:
// setTimeout
function myFunction(){
setTimeout(myFunction, 100);
doSomething();
}
setTimeout(myFunction, 100);
// setInterval
function myFunction(){
doSomething();
}
setInterval(myFunction, 100);
Passing in a string fires up a JavaScript parser and does the same thing as eval. It should be avoided whenever possible (and it's almost always possible).
T.J. Crowder explained the main differences, one other more subtle could appear (I change the time scale as it's easier to explain) :
Lets plot the difference with a very big timeout time : 1 Day. You call both methods at 00:00 on Day 1 and let it run for 1 year...
1 Year latter your method called by setInterval will execute at 00:00 + some milliseconds (because you may not be the only one asking for the processors to do things at this exact moment and the OS timers have granularity anyway).
But your setTimeout method will occur latter, maybe around 00:01 because each day it would have been called a little after the requested time and requested to be called the next day at the same time...
PS: It could also be called before the requested time in some cases but more often than not it run after :-D