JavaScript setTimeout() won't wait to Execute? [duplicate] - javascript

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 2 years ago.
Consider the following example:
<script type="text/javascript">
function alertBox(){
alert('Hello World!');
}
function doSomething(){
setInterval(alertBox(), 5000); //This is for generic purposes only
};
function myFunction(){
setTimeout(doSomething(),3000);
};
myFunction();
</script>
What is it that causes this to execute IMMEDIATELY, rather than waiting the 3 seconds set, as well as only executing the alert ONCE, rather than at the scheduled 5 second intervals?
Thanks for any help you can provide!
Mason

alertBox()
Doesn't this look like an immediate function call?
Try passing the function (without executing it) instead:
setInterval(alertBox, 5000);

its because you are executing the function, not passing a function object.
function myFunction(){
setTimeout(doSomething, 3000); // no () on the function
};

Following codes executing differently,
setTimeout(console.log('Nuwan'),0)---(A); and
setTimeout(function(){console.log('Nuwan'),0}) --- (B)
The reason is when (B) is executing, CallStack in javascript runtime push the setTimeout() to web API and
WebAPI waits 0 seconds to push the callback function to the event queue and then EventLoop pushes the callback to the stack after the current stack is empty.
In Case (A), console.log() directly calling because it is in the WepAPI, no need to go for an event loop to execute.
More Ref:
WebAPIs: https://developer.mozilla.org/en-US/docs/Web/API/Console_API
Javascript Runtime and Event Loop: https://cybrohosting.com/knowledgebase/17/How-JavaScript-works-in-browser-and-node.html

Related

setTimeout function executing code without any delay . Javascript [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 2 years ago.
Can anyone explain why this is happening. I have created a function in JS and trying to call it after 60 seconds using setTimeout function. But it runs right away after the page loads. Why is this happening and setTimeout is not delaying the function code? Below is the code.
<script>
function first()
{
document.getElementById('addProductText').style.color="#32A067";
}
setTimeout(first(),60000);
</script>
Use your call to the function without the brackets ():
setTimeout(first, 6000);
This way you are referencing to the function, and not calling it immediately.
Working example:
function first() {
document.getElementById('addProductText').style.color = "#32A067";
}
setTimeout(first, 6000);
<div id="addProductText">Hello World!</div>
You should only pass the name of the function without calling it:
function first(){
console.log("Hello")
}
setTimeout(first, 60000);

The difference between using setTimeout(fn, 0) and not using it [duplicate]

This question already has answers here:
Why is setTimeout(fn, 0) sometimes useful?
(19 answers)
Closed 3 years ago.
I have a simple question about setTimeout function
My function:
function myFunc(){
// some code here
}
What's different when
I call a function with and without setTimeout:
myFunc();
setTimeout(function(){
myFunc();
}, 0);
Can someone explain help me? Thank you.
setTimeout waits for a given delay then schedules a new task for its callback. This is why setTimeout is logged after script end, as logging script end is part of the first task, and setTimeout is logged in a separate task. Right, we're almost through this, but I need you to stay strong for this next bit…
Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates. Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.
https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
setTimeout(,0) will call after all current queue will be finished, and
normal function call goes in the queue first.
You can see here:
function myFunc1(){
console.log("In myFunc1");
}
function myFunc2(){
console.log("In myFunc2");
}
setTimeout(function(){
myFunc1();
}, 0);
myFunc2();

JS Callback is not working [duplicate]

This question already has answers here:
setTimeout function doesnt stop execution?
(2 answers)
Closed 4 years ago.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function f() {
g(function(err){
if(!err){
alert('Call me later');
}
});
}
function g(callback) {
setTimeout(function(){ alert("Call me first after 3 sec"); }, 3000);
callback(false);
}
</SCRIPT>
</HEAD>
<BODY onload="f()">
</BODY>
</HTML>
In the above code snippet my objective is to understand the JavaScript callback feature.
I put two alerts in. I had wanted 'Call me first' to alert after 3 sec and then 'Call me later'. However, this is not the order the the alerts occur.
This has to do with the asynchronous call you made.
Calling the function g will take two actions for its two lines of code. First, it will create a task and schedule it to run in 3000 milliseconds. Second, it will call the callback. The callback then alerts 'Call me later'.
If the code in the timeout had called the callback, then call me later would have come second, but since it did not, and the timeout is not a blocking call, you see the current behavior.
If you wanted the alert to come second, the timeout should make the call.
function g(callback) {
setTimeout(function(){
alert("Call me first after 3 sec");
callback(false);
}, 3000);
}
Script tag has no such attribute as 'language'.
Instead of
<SCRIPT LANGUAGE="JavaScript">
try
<script type="javaccript">

Call Stack while using setTimeout()

I am a bit confused about setTimeout.I want to confirm whether the output for the following code will always be:
inside abc
inside sample
The code:
function abc() {
xyz();
// interactions and modifications in DOM
$("#id1").append("something");
$("#id2").val("set something");
$("#id3").after("create some dynamic element");
// 10 to 20 interaction more...
console.log('inside abc');
}
function xyz() {
setTimeout(function() {
sample();
},0);
}
function sample() {
console.log('inside sample')
}
It would be great,if somebody could explain the whole flow with the call stack.
Yes, it will always have that output.
The callback inside a setTimeout will not be called until the execution context is clear - i.e. the currently executing sequence of code has finished.
This means that even if you do
setTimeout(function () { console.log("1 second!"); }, 1000);
var start = +new Date();
while ((+new Date()) - start < 5000) {}
1 second! will not be logged any sooner than 5 seconds have passed.
setTimeout() will run asynchronously after finishing current execution block. So output should be same always:
inside abc
inside sample
Javascript internally manage an event queues internally for all async tasks. Every time it checks its async queue after finishing current execution block.
Yes, the console output will always be the same. setTimeout's callback function is executed asynchronously after the context that called it is cleared. When setTimeout is called, it places its callback function on the stack and returns to the current execution context. When that is done (in your example, when abc is fully executed), the callback function is executed, which in your example basically calls sample immediately. So your code output will never be different.
The fact that setTimeout's callbacks are themselves executed asynchronously can be seen if you placed a longer setTimeout function somewhere inside abc before calling xyz:
function abc() {
setTimeout(function(){
console.log('wait')
},1000);
xyz();
console.log('inside abc');
}
function xyz() {
setTimeout(function(){
sample();
} ,0);
}
function sample() {
console.log('inside sample');
}
abc();
...your console will log:
inside abc
inside sample
wait
To hold sample's execution until the longer timeout is complete you would need to place the setTimeout calling sample inside the longer setTimeout.
If setTimeout's callback is ever behaving differently, it's most likely due to being accidentally passed a function call instead of a function pointer, like this:
setTimeout(sample(),0);
instead of
setTimeout(sample,0)
Also, just in case you didn't know (or for others), you can add
debugger;
at any point(s) in your Javascript code and then run the code to view the callstack at that point using dev tools (in Chrome it is in the right panel under 'Sources').

Javascript SetInterval not waiting properly? [duplicate]

This question already has answers here:
Jquery setInterval() not working
(5 answers)
Closed 9 years ago.
In my javascript I have:
$(document).ready(function ()
{
setInterval(test('test alert'), 10000);
});
function test(value)
{
alert(value);
}
Simple, when the document is ready, it should set up the setInterval... Which basically means, wait 10 seconds, run the function, then repeat every 10 seconds.
The problem is the setInterval is not activating properly. The test function is being fired immediately (instead of waiting 10 seconds), and never fires again subsequent times. What am I doing wrong here?
Now, if I set up my setInterval as follows, it works fine... but why?
setInterval(function() { test('test alert'); }, 10000);
That's because you're passing the return value of invoking the function, not the function itself. What you want is this:
setInterval(test, 10000);
If you need to pass an argument into the test, you have to wrap it in another function:
setInterval(function(){test('test alert');}, 10000);
Whenever you use a literal followed by parenthesis (like test() or test('test alert'), the parentheses are a signal to JavaScript to invoke the function. To test this for yourself, try the following in an interactive console in your browser:
console.log('test: ' + test);
console.log('test(): ' + test());
The first will tell you that the value is a function; the second will tell you undefined; that's because the function (test) has been invoked, and the value returned.
Note that in JavaScript, functions are first-class citizens, so there's nothing wrong with creating a function that itself returns a function:
function test(value) {
return function(){
alert(value);
}
}
If you did that, your setInterval would work as you originally expected it to:
// test('test alert') returns a function
setInterval(test('test alert'), 10000);
setInterval() expects a function or an eval()-able string as its first argument. In your code, you are passing it the return value of the function test()
Instead it should be:
setInterval(function() {
test('test alert');
}, 10000);

Categories

Resources