To delay JavaScript function call using jQuery - javascript

JavaScript:
$(document).ready(function(){
function sample() {
alert("This is sample function");
}
$("#button").click(function(){
t = setTimeout("sample()",2000);
});
});
HTML:
<input type="button" id="button" value="Call sample function with delay">
Once I click the button, sample() function is not called with a delay of 2 seconds. I don't know what's wrong.
How to call JavaScript function using setTimeout() via jQuery?

Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.
You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout, using eval is inefficient and hard to debug.
setTimeout(sample,2000)

function sample() {
alert("This is sample function");
}
$(function() {
$("#button").click(function() {
setTimeout(sample, 2000);
});
});
jsFiddle.
If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().

Very easy, just call the function within a specific amount of milliseconds using setTimeout()
setTimeout(myFunction, 2000)
function myFunction() {
alert('Was called after 2 seconds');
}
Or you can even initiate the function inside the timeout, like so:
setTimeout(function() {
alert('Was called after 2 seconds');
}, 2000)

Related

why the function method inside of the object doesnt work? [duplicate]

How come I can say:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
Why does the function call in the setTimeout not require parentheses, but the last line does?
Nutshell
myFunction references the function
myFunction() calls the function
More Words
setTimeout expects a function reference* as an argument.
There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
setTimeout gets the return value of myFunction
myFunction returns a function (that calls alert)
meaning there will be an alert every second.
See also Why function statement requires a name?
* Or a string to be evaluated, but a reference is preferred.
myFunction is a function
myFunction() calls the function and yields whatever value the function returns.
The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.
When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).
In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.
I think this example would make it clearer if i may,
function callback() {
console.log('this function runs on page loads.');
}
setTimeout(callback(), 2000);
Here callback() function will run immediately after page loads and won't wait 2 seconds.
function callback() {
console.log('this function runs after page loads.');
}
setTimeout(callback, 2000);
Here callback() function will run after 2 seconds.

Javascript callbacks not working as expected .? Want to know what is causing an error as such .? [duplicate]

How come I can say:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
Why does the function call in the setTimeout not require parentheses, but the last line does?
Nutshell
myFunction references the function
myFunction() calls the function
More Words
setTimeout expects a function reference* as an argument.
There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
setTimeout gets the return value of myFunction
myFunction returns a function (that calls alert)
meaning there will be an alert every second.
See also Why function statement requires a name?
* Or a string to be evaluated, but a reference is preferred.
myFunction is a function
myFunction() calls the function and yields whatever value the function returns.
The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.
When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).
In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.
I think this example would make it clearer if i may,
function callback() {
console.log('this function runs on page loads.');
}
setTimeout(callback(), 2000);
Here callback() function will run immediately after page loads and won't wait 2 seconds.
function callback() {
console.log('this function runs after page loads.');
}
setTimeout(callback, 2000);
Here callback() function will run after 2 seconds.

Why do I need to call a function but not a method?

in Node.js I have this code:
console.log('starting');
function sayHello() {
console.log('HEllo!!');
}
setTimeout(() => {
console.log('inside of callback');
}, 1000);
console.log('finishing app');
Why if I run through the terminal the (App) file it displays the result of the setTimeout function but not the sayHello? After all, I did not call the setTimeout function either!
Moreover, if then I store the setTimeout function in a variable like
var x = setTimeout(() => {
console.log('inside of callback');
}, 1000);
the function is called automatically as well! Why?
There is no link with function or method here. It's about declaration and call.
When you do :
function sayHello() {
console.log('HEllo!!');
}
You declare a function sayHello that won't be called. To call it, you need to do sayHello(); after declare it.
When you use setTimeout(), you are calling a built-in function already declared for you by JavaScript. To know how to use the function that is already declared, you need to check a documentation of the function. Example : check here (part syntax).
Note : Every function in JavaScript is attached to an object, so every function is a method. setTimeout, for example, is attached to the global object (in browser, it's window, in Node it's global). Your sayHello() function will be also attached to her scope.
The implementation of setTimeout is something like (this is only a mock implementation):
function setTimeout(callback, interval, ....args) {
// wait for `interval` time to pass
callback(...args);
}
As you can see, setTimeout is a function which takes a function(callback in the above example) as a parameter, and calls that function after interval time has passed.

javascript function need to be continue after settimeout

I have a JavaScript function; from that am calling a delay function.
function(){
// code
doDelay();
// some other functionality....
}
function doDelay(){
setTimeout(function() {alert("after wait");}, 10000);
}
after waiting 10 seconds alert is coming after wait. but its not again continue the some other functionality.... of my main function.. After delay I want to execute the remaining functionality. How can I do that?
The setTimeout function does not delay execution. Instead, it schedules a function to be executed at a later time. To do what you want you need to change your code to this:
function(){
...
...
doDelay(function(){
some other functionality....
});
}
function doDelay(callback){
setTimeout(function() {callback()}, 10000);
}
Indeed, javascript already has a doDelay function. It's called setTimeout:
function(){
...
...
setTimeout(function(){
some other functionality....
},10000);
}
If you want the outer function to also delay execution of code that comes after it, you also need to pass a callback to it:
function foo (callback){
...
...
doDelay(function(){
some other functionality....
callback();
});
}
So that, for example, it allows you to rewrite something like this:
foo();
// do other stuff after foo...
to this:
foo(function(){
// do other stuff after foo...
});
You basically need to restructure your logic around callbacks.
Can't you wrap the other functionality in another function, then from your SetTimeout call that function?
function(){
doDelay();
}
function doDelay(){
setTimeout(function() {alert("after wait");andTheRest();}, 10000);
}
function andTheRest(){
//Rest of the stuff here
}
doDelayAndThenContinue(){
setTimeout(function() {alert("after wait");
//do other functionality here
}, 10000);
}
Remove the do other functionality from main method and put in setTimeout

Function in function cycle

i need to load PHP file with random image to <div> every 2 seconds with fade effect so i use javascript and jQuery. I write function to hide div, load file in, than show it and wait 2 seconds, then it should call function again, but it happend just once then it stop.
Here is the function:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'}).delay(2000, function(){
random();
});
random();
Do this:
(function random(){
var timer;
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php", function(){
$(this).animate({opacity: '1'});
timer = setTimeout(random, 2000);
});
})();
Here we create self-invoking function and call it inside setTimeout so that it gets called again and again AFTER your image loading and animation part is complete. You would need to call clearTimeout(timer) to stop running setTimeout once all your images are loaded.
try adding setTimeout(random, 2000); after the load request is completed:
function random(){
var rndImg = $("#randomImage1");
rndImg.fadeOut().load("../images/randomImage.php",function(){
rndImg.fadeIn();
setTimeout(random, 2000);
});
};
random()
The problem you have is that you're trying to use .delay() as a replacement for the native setTimeout(), which isn't what it's intended to do. The .delay() function is designed to add a pause between jQuery animation effects, not to delay the execution of another function, and doesn't accept a callback function. See the jQuery documentation for the .delay() function.
As has already been covered in previous answers, you can use the native setInterval() function to implement the delay you're after:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php").animate({opacity: '1.0'});
setInterval(random, 2000);
}
random();
Note that this will animate the #randomImage1 element back to full opacity, and set the interval to call the function again, even if the AJAX call from .load() didn't return a success response. If that's not what you want, you can instead move that code into an anonymous function passed as the success callback on .load(), like so:
function random(){
$("#randomImage1").animate({opacity: '0.0'}).load("../images/randomImage.php",
function() {
$("#randomImage1").animate({opacity: '1.0'});
setInterval(random, 2000)
});
}
random();

Categories

Resources