why can use setTimeout("1") - javascript

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"))

Related

why do I set a variable for generator after setting a variable for a generator again ? (This case is different from ordinary generator examples)

After setting a variable for a generator like
let gene = generator();
Normally, What I need to do is
gene.next() to iterating the generator made above.
However, in this example below, (For the full code, please refer to the link)
https://codepen.io/jotnajoa/pen/MWwzpJJ
another variable is set after set a variable for the generator again.
I don't know why this is happening. Also, I don't get the part of
let result = genratorAnimation.next();
//genratorAnimation.next();
let interval = setInterval(function(){
if(!result.done) {
genratorAnimation.next();
}
else {
clearInterval(interval)
}
}, 50);
At the end of this code.
Because, to my understanding, generator returns 'true' for 'done' when everything is yielded.
However, in this example, it is doing the opposite thing. which is "not result.done" which is false while running the generator.
Why is it?
As a summary,
1) why do I need to set another variable for interval.
I assumed, setInterval( ######## ) is enough, instead of let xxx = setInterval to run the loop.
because, if I set the variable for setInterval,
nothing would happend till I type the variable 'xxx'. But in this code, it is running even if I do not call the variable.
2) Why !result.done makes the loop plays.
because !result.done is false and if false is within if statement, things comes after if wouldn't run.
If statement runs only when the condition is true.
Isn't it?
Thank you in advance.
why do I need to set another variable for interval.
setInterval() is used to repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. this means that the function provided to setInterval() function will be called and executed forever if its not stop by calling clearInterval() function.
clearInterval() require a interval reference (variable), in this snippet we can have the code without clearing the interval but it will keep running and consume resources memory/CPU with no effect in the end so its better to remove it from the execution queue.
Why !result.done makes the loop plays.
The generator function will keep returning result.done as false until its last result returned, it will return true: and ! (Logical NOT) used to negate a Boolean value so if result.done is false, !result.done will negate it and make it true. the way its written in your code snippet, is a matter of coding style it can be written as:
let result = genratorAnimation.next();
//genratorAnimation.next();
let interval = setInterval(function(){
if(result.done) {
clearInterval(interval);
}
else {
genratorAnimation.next();
}
}, 50);

Weird behavior in xpage/javascript variable assignment

I'm having this weird behavior and I'm not sure if it's me not misunderstanding variables or it's an xpage issue
I have a document with a field called "hours" and it has a value of 8.
Here is my simplified code .
var xHrs = doc.getItemValueDouble('hours');
println (xHrs); // at this point, hours is 8
doc.replaceItemValue('hours', 0);
return xHrs; // returns 0;
Why is xHrs back to 0 when I replace the document value to 0? How do I break the link?
Thanks in advance for the help :)
R.
Chances are that the code is being executed more than once.
Try wrapping the code with ${javascript: rather than #{javascript:
${javascript:
var xHrs = doc.getItemValueDouble('hours');
doc.replaceItemValue('hours', 0);
return xHrs;
}
The code will be executed only once with the preceding $.
I suspect that setting your xHrs variable as you do creates a function expression that returns the value of the 'hours' field. You change the value of the field and the function returns the new value.
I'm not sure about breaking the chain in an efficient manner, but maybe if you create a second variable to hold the xHrs value?

What happens when you use WinJS.Promise.Timeout(undefined)?

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.

Pass Hash from URL to a Function with Delay

I am trying to pass a has such as http://mysite.com/#32132 via JS to a custom function.
Here's the function:
var downloadVideo = function(passed){
console.log(passed);
}
And here's how I'm getting and passing the hash from the URL:
if(window.location.hash){
var hash = window.location.hash;
hash = hash.substring(1, hash.length); // Remove the # from the hash
setTimeout('downloadVideo('+hash+')', 3000)
}
After 3 seconds, I just get an error in the console:
Uncaught ReferenceError: 32132 is not defined
I've tried different ways of calling downloadVideo. With quotes, without quotes, without the plus signs. Nothing seems to work. If I console.log the hash var immediately before the setTimeout it displays it correctly.
You need to represent it as a string if there's anything more than just numeric characters...
// ------------------v--------v
setTimeout('downloadVideo("'+hash+'")', 3000);
But better to pass a function that closes over hash...
setTimeout(function() { downloadVideo(hash) }, 3000);
You can use a closure to do that:
setTimeout(function() {
downloadVideo(hash);
}, 3000);
1) You don't need the second argument in your has substring - if omitted, the substring matches to the end of the string
2) with timeouts it's better to use anonymous functions; evaluated strings are, well, evaluated. Generally a bad idea.
3) the error is coming because you're passing a string without quotes. Fixing point 2 to use an anonymous function would make this error both more visible and harder to commit in the first place
4) you could always apply the timeout in the function, rather than in the call to it
Anyway:
setTimeout(function() { downloadVideo(hash); }, 3000);
Assume that the value of hash is test then:
'downloadVideo('+hash+')'
...evaluates to:
downloadVideo(test)
Notice that there are no quotes around the string test so it's treated as though it refers to a variable (that doesn't exist). This is one of many reasons not to pass strings to setTimeout. It's a bad practice, as described here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/eval#Don%27t_use_eval!
It's far better to pass a function to setTimeout. It's safer, easier to read, and doesn't suffer from the problem you've see here. When no arguments are required, simply refer to the function by name:
setTimeout(downloadVideo, 3000)
If arguments are required, as they are in your case, then you'll need to pass a reference to an anonymous function and have that function call the function that you want to invoke:
setTimeout(function() {
downloadVideo(hash);
}, 3000)

Is there a way in javascript to see if a variable has a timeout assigned to it?

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.

Categories