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">
Related
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);
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();
This question already has answers here:
How to delay calling of javascript function?
(5 answers)
Closed 3 months ago.
I’m trying to make a script that clicks on a page button, waits X seconds (for the result of the click to take place), and then continues.
How can I implement the waiting part?
using setTimeout, which executes only once after the delay provided
setTimeout(function(){
console.log('gets printed only once after 3 seconds')
//logic
},3000);
using setInterval , which executes repeatedly after the delay provided
setInterval(function(){
console.log('get printed on every 3 second ')
},3000);
clearTimeout and clearInterval is used to clear them up !!!
You want to use setTimeout() which executes a code snippet after a specified delay.:
var timeoutID;
function delayedAlert() {
timeoutID = setTimeout(slowAlert, 2000);
}
function slowAlert() {
alert("That was really slow!");
}
function clearAlert() {
clearTimeout(timeoutID);
}
<p>Live Example</p>
<button onclick="delayedAlert();">Show an alert box after two seconds</button>
<p></p>
<button onclick="clearAlert();">Cancel alert before it happens</button>
Or you can use setInterval() which calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function:
function KeepSayingHello(){
setInterval(function () {alert("Hello")}, 3000);
}
<button onclick="KeepSayingHello()">Click me to keep saying hello every 3 seconds</button>
Somehow setTimeout doesn't do anything for me. But window.setTimeout does.
window.setTimeout(function() {
alert("Hello! This runs after 5 seconds delay!");
}, 5000);
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);
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