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

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

Related

How to use function in settimeout for milliseconds in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I use an ajax call to get the value of timer from the server. And I have to use that value for timeout in setTimeout() method. How to use functions instead of an actual value.
Here is my code:
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
getTimerValue() is my ajax call to the server. It works fine if I use an value like 5000 instead of the function. Please help me to solve this. Thanks in advance!
Update - Solved:
There was an issue with my ajax call. It was returning undefined. After adding callback option, it works fine.
Please check this example.
var isStopped = true;
function getTimerValue() {
return 5000;
}
function stopLoading() {
console.log('ok')
}
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
As i set isStopped to true so its insert the if condition then its set the setTimeout function. but as i set it to execute it after 5000 so it will wait in the mean time it will execute the next line console.log("Stopped loading image"); and the after 5000 it prints ok
Hope This will help

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();

Why clearInterval doesn't work if the setInterval was inside the function? [duplicate]

This question already has answers here:
How can I use setInterval and clearInterval?
(5 answers)
Stop setInterval
(6 answers)
Closed 5 years ago.
function consoleTest() {
setInterval(function(){
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function(){
clearInterval(consoleTest);
});
consoleTest();
I created a simple app when I click the button it will stop/pause the interval. I know how to make it work I just need to declare a variable outside the function and contain there the setInterval, now I am just confused why clearInterval won't work if I call it via a function, somebody please explain it to me.
This is the correct usage of setInterval and cleaInterval.
setInterval returnes a value which you need to keep in a variable scoped for both function. When you want to clear the interval, use clearInterval and pass it the variable as a parameter:
var interval;
function consoleTest() {
interval = setInterval(function() {
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function() {
clearInterval(interval);
});
consoleTest();
For further reading: clearInterval and setInterval.
There's two issues here. Firstly you don't set the returned timer id from setInterval() anywhere. consoleTest is the function that wraps the timer, not a reference to the timer, which is what should be given to clearInterval(). Secondly, you need that timer reference to be in scope of both functions. With that in mind, try this:
function consoleTest() {
return setInterval(function(){
console.log('Hello World');
}, 1000);
}
$('#button').on('click', function(){
clearInterval(interval);
});
var interval = consoleTest();

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

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

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

Categories

Resources