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();
Related
I wanted to have a better understanding of how the event loop and asynchronous code works in Javascript. There is a ton of resources online but I could not find an answer to my question
Everyday I mostly use callbacks, promises, async/awaits, but at the end I am simply relying on already asynchronous methods.
Therefore I wanted to know how it works, creating an async function from scratch, and deal with blocking code (or should I say slow code, that is not an HttpRequest or anything that is already provided to us).
For example taking while loop with a very high condition to stop it, should take a second to finish. And this is what I decided to implement for my tests.
After my research, I could read that one way of making my code asynchronous, would be to use setTimeout with a 0ms delay (placing a message in the event queue, that will be executed after the next tick)
function longOperation(cb) {
setTimeout(function() {
var i = 0;
while (i != 1000000000) { i++; }
cb();
}, 0);
}
longOperation(() => {
console.log('callback finished');
})
console.log('start');
My question is:
When my code is finally going to be executed, why isn't it blocking anymore ? What is the difference between executing it normally, and placing a message that the event loop will pick to push it to the call stack ?
The following video shows how the event loop handles a setTimeout with 0 delay.
JavaScript Event loop with setTimeout 0
However, the code executed is a simple console log. In my example, this is a "long" operation...
The outer code executes to completion.
The setTimeout 0 timer expires immediately, so its callback runs right away and executes to completion (the long-running while loop and its callback).
During both of these code execution phases, no other JavaScript user code will run.
This question already has answers here:
javascript interval
(3 answers)
Closed 6 years ago.
I am fairly new to JavaScript, and I am learning it through p5 and videos by Daniel Shiffman.
I've been looking for a way to update a program every minute or so that checks a weather api, so I don't have to refresh the page myself.
I am aware that there are already answers to this question on here, but none of them make sense to me, as I am very new to JS.
So if you could answer it with an ELI5 ("Explain it like I'm five") description that would great.
setInterval() is your easiest option.
Take a look at this simple example:
// Will execute myCallback every 0.5 seconds
var intervalID = window.setInterval(myCallback, 500);
function myCallback() {
// Your code here
}
More information and more examples can be found here: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval (https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval)
In plain vanilla Javascript, you would use setInterval:
var intervalID = window.setInterval(checkWeatherAPI, 60000);
function checkWeatherAPI() {
// go check API
console.log("checking weather API");
}
If you were to run the above, the callback function: checkWeatherAPI, would run once every minute, or 60,000 milliseconds forever, full documentation here: WindwTimers.setInterval
To stop the interval you would simply run this line:
window.clearInterval(intervalID);
Choosing whether setInterval OR setTimeout is based on your need and requirement as explained a bit about the difference below.
setInterval will be called irrespective of the time taken by the API. For an instance you set an API call every 5 seconds and your API call is taking 6 seconds due to the network latency or server latency, the below setInterval will trigger the second API call before the first API completes.
var timer = setInterval(callAPI, 5000);
function callAPI() {
// TO DO
triggerXhrRequest(function(success){
});
}
Instead, if you want to trigger another API call after 5 seconds once the first API call completed, you can better use setTimeout as below.
var timer = setTimeout(callAPI, 5000);
function callAPI() {
// TO DO
triggerXhrRequest(function(success){
timer = setTimeout(callAPI, 5000);
});
}
setTimeout will be called once after nth seconds. So you can control when the next one can be called as above.
MDN Documentation
setTimeout
setInterval
function doThings() {
// The things I want to do (or increment)
}
setTimeout(doThings, 1000); // Milliseconds
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have this function which is using namespace. I want to make it asynchronous. Assuming that this function is being called on click of some button ?
var ns = {
somemfunc: function (data) {
alert("hello");
}
}
EDIT - Sorry for being unclear on this. I want to make the call to this function asynchronous by putting the settimeout function inside the somefunc function. Not sure how to do that.
Thanks in advance
You can set this function to be called asynchronously by adding a setTimeout block within the definition of somefunc, note that I am using the term asynchronous loosely here as this function isn't really doing any asynchronous work. An async function would be a function that does some work that takes some time to execute, such as making a network request, aggregating its results and then reporting back to the caller to do some sort of DOM refresh or something, it normally reports back to the caller using a callback, or resolving/rejecting a promise, in the time that this long running code is running, the Event Queue is not blocked and can continue to process other actions if this was not the case then the app would be unresponsive until the long running task finished computing.
What you want to achieve here is not truly async as you're simply scheduling the function to run on the Event Queue in 2 seconds.
var ns = {
somemfunc: function (data) {
setTimeout(function() {
alert("hello");
}, 2000);
}
}
ns.somemfunc();
When ns.somefunc() is called, its now set to execute the function somefunc on the Event Queue in 2000ms (2 seconds). Remember Javascript is single threaded, tasks are scheduled to run on the event queue and will be processed contiguously. If you set the timeout to run the function after 2000ms but the jobs before it take 500ms to compute, then we actually wait 2500ms for the queue to serve that function.
I want to call a function in JavaScript continuously, for example each 5 seconds until a cancel event.
I tried to use setTimeout and call it in my function
function init()
{ setTimeout(init, 5000);
// do sthg
}
my problem is that the calls stops after like 2 min and my program is a little bit longer like 5 min.
How can i keep calling my function as long as i want to.
thanks in advance
The only conceivable explanations of the behavior you describe are that:
As another poster mentioned, init is somehow getting overwritten in the course of executing itself, in the // do sthg portion of your code
The page is being reloaded.
The //do sthg code is going into some kind of error state which makes it looks as if it not executing.
To guarantee that init is not modified, try passing the // do sthg part as a function which we will call callback:
function startLoop(callback, ms) {
(function loop() {
if (cancel) return;
setTimeout(loop, ms);
callback();
}());
}
Other posters have suggested using setInterval. That's fine, but there's
nothing fundamentally wrong with setting up repeating actions using setTimeout with the function itself issuing the next setTimeout as you are doing. it's a common, well-accepted alternative to setting up repeating actions. Among other advantages, it permits the subsequent timeouts to be tuned in terms of their behavior, especially the timeout interval, if that's an issue. If the code were to be rewritten using requestAnimationFrame, as it probably should be, then there is no alternative but to issue the next request within the callback, because requestAnimationFrame has no setInterval analog.
That function is called setInterval.
var interval = setInterval(init, 5000);
// to cancel
clearInterval(interval);
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