Need clarification on setTimeout function output - javascript

I have one doubt in java script.I opened https://stackoverflow.com and then open developer window(by press f12 or inspect) and went to console and then execute below code.
setTimeout(function(){console.log('hello..')},5000);
output:
8
hello..
once I click on enter first display 8 after 5 sec it displays hello.. text.
Now my question is what is that number here(8), it is changed for different, different domains.

This is the returned value of setTimeout :
The returned timeoutID is a positive integer value which identifies
the timer created by the call to setTimeout(); this value can be
passed to clearTimeout() to cancel the timeout.

That is the ID of the timeout you've just set and you can use it to cancel it.
For example:
var timeoutId = setTimeout(fn, delay);
clearTimeout(timeoutId);
If the clearTimeout function is called before the delay, the fn function will never be executed.
You can find more details about setTimeout HERE

Related

javascript auto submit result in a loop

A php page (let's call it page_one) checks certain values on DB and echoes different questions on screen depending on those values. The user sets some radios and click submit. The code send the radio values to another php file (let's call it page_two) where they are written in the DB and then the code puts new values in hidden fields of a hidden form and submits them loading again page_one, where new questions are presented. And so on till the number of questions-set is finished.
To auto-submit to page_one I use the following javascript inside the php file page_two.
<script>
var auto_refresh = setInterval(function() { submitform(); }, 50);
function submitform()
{
/*alert('test');*/
document.getElementById("hidden-form").submit();
}
</script>
On Firefox (Mac) and Safari (Mac) and iOS(Safari) everything goes right: page_two writes the values in the db and calls back page_one.
Instead of doing the same, Chrome enters in a loop, and continues to call page_two every 50 ms, for thousands of times till something breaks all that.
Any help?
Thats what setInterval is made for.. it will run for every 50 mili seconds and submit the form.. if you need it to call it once then use setTimeout.
The setInterval() method calls a function or evaluates an expression
at specified intervals (in milliseconds). The setInterval() method
will continue calling the function until clearInterval() is called, or
the window is closed.
reference: setInterval
The setTimeout() method calls a function or evaluates an expression
after a specified number of milliseconds.
reference: setTimeout

Unexpected setTimeOut() function behavior in JavaScript

I came across this simple(or what I thought so) question on a Javascript MCQ Test:
After how much time will the following code execute entirely?
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
setTimeOut(console.log("hi"),1000);
Options
A) 1 second
B) 2 seconds
C) 4 seconds
D) 5 seconds
I answered as option D) 5 seconds since EACH line above will take 1000 milliseconds to execute i.e a total of 5000 milliseconds = 5 seconds
But in the results, it said that the actual answer is Option A) 1 second.
I executed those five lines in my console (altogether) and the entire code executed after 1 second like the answer said.
I don't understand the logic behind the right answer, and why my reasoning was wrong.
because setTimeout works asynchronously, means all of these 5 statements will be executed simultaneously and all of these will start waiting for 1 second. and after one second all will be executed. hope it clears.
Each call you make it running in it's own background thread (it's own unique operation), when you call setTimeout, you're telling JavaScript that you want to execute your code after 1 second has passed.
If you wanted to make this last 5 seconds you would do something along the lines of:
setTimeout(function() {
console.log("First task")
setTimeout(function() {
console.log("Second task");
},1000);
},1000);
This would execute the first task, once called it will execute the second task
Edit: I saw another post about doing it non-async, you want to avoid doing anything non-async in JavaScript as it will hold up the browser which is general is a bad practice and bad user experience
From the MDN page:
The setTimeout() method ... sets a timer which executes a
function or specified piece of code once the timer expires.

Timeout/Sleep in NightWatch/JavaScript

How to input between lines of code some force-timeout (like java Thread.Sleep) in NighWatch.js ?
Have to wait for element to have exact value after page render.
I don't think this is the correct answer. For the original poster it's probably too late but other users might google it:
If you use the Nightwatch testing frame work then you can use these commands:
http://nightwatchjs.org/api#pause
browser.pause(1000); // pauses the test for 1000 milliseconds
or wait for an element to be present:
browser.waitForElementPresent('body', 1000); // waits max. 1000 ms for the element to appear
You won't be able to stop the thread since javascript is single thread non blocking.
What you want to do is this
setInterval(function () {alert("Hello")}, 3000);
The syntax is.
window.setInterval("javascript function", milliseconds);
See : http://www.w3schools.com/js/js_timing.asp

jQuery setInterval from getScript

I am trying to get a script from one page and get it again after a certain period of time. But, the time varies each time. On the main page I have
function varcontent() {
$.getScript("custom.php");
}
varcontent();
Then on the custom.php I have my script and
setInterval(varcontent, 20000);
at the end. Each time it may not be 20 seconds. It seems to work at first, but then the old ones are fired again too. I don't know how to get it out of this loop and they keep multiplying.
You probably want setTimeout, not setInterval. setInterval will keep invoking the callback (until you cancel it), whereas setTimeout will only invoke the callback once after the specified delay.
So in your custom.php, you should have instead:
setTimeout(varcontent, 20000);

what's the difference between javascript timeout and timer methods

JS support timeout and timer. Here is their definition:
timeout - repeat execution of a code within specific time and it returns an integer that can be used to cancel pending timeout.
var timeout_id = setTimeout(f,500);
cleartTimeout(timeout_id);
timer - repeat exectuion of code at specific interval.
id = setInterval(F,5000);
clearInterval(id)
I am a little confused, what is their difference?
setTimeout executes the code only once.
setInterval executes the code at every xxx amount of time.
Interval repeats indefinitely (unless you clear it)
Timout repeats once (unless you clear it)
See the difference in this demo: http://jsfiddle.net/maniator/KS2pF/
setInterval will continue to run repeatedly until you stop it, setTimeout will run once.
Start using MDN Docs:
setTimeout
setinterval

Categories

Resources