Sequence of setTimeout in JavaScript - javascript

Can someone explain me, why if I create a function in JavaScript and add it to setTimeout, setTimeout doesn't work properly, but if I create anonymous function everything is okay? Example below:
It works:
setTimeout(function() {
alert("foo");
}, 100);
It doesn't works:
function foo() {
alert('foo');
}
setTimeout(foo, 100);

I checked your code, you are accessing snakeTail inside setTimeout callback. When callback function is executed after 100 ms the variable snakeTail is not available anymore. You should replace your line with
setTimeout(function(param){
alert("Game over! Your score: "+(param-5)+" points. Wanna play again?");
location.reload();
}, 100, snakeTail);
This way you can save the snaketail variable and pass it inside setTimeout callback.

Undersatanding setTimeout
There is no difference, how to use it, passing anonymous function to setTimeout:
setTimeout(function() {
console.log("foo");
}, 1000);
Or passing an existing function:
function foo() {
console.log('foo');
}
setTimeout(foo, 1000);
setTimeout is an asynchronous, so if you will use it before the regular console.log, the console.log after setTimeout function will be printed first, and then, the console.log inside setTimeout will be printed after specified delay (1 second in this case):
setTimeout(function() {
console.log("bar");
}, 1000);
console.log("foo");
But if you want to log "foo" after 1 second and then to log "bar" after one second from "foo" was logged, you can add 2 second delay to the second setTimeout, like this:
setTimeout(function() {
console.log("foo");
}, 1000);
function bar() {
console.log('bar');
}
setTimeout(bar, 2000);
Or alternatively you can wrap one setTimeout into another and give both of the 1 second delay. In this case, after 1 second will be printed "foo", and after 2 seconds will be printed "bar":
setTimeout(function() {
console.log("foo");
setTimeout(bar, 1000);
}, 1000);
function bar() {
console.log('bar');
}
Hope this will give you the basic understanding of how setTimeout works.

Related

How to use call back to make a function execute after another in setTimeout condition

I have some code which can be mimicked by this situation
function abc(def){
setTimeout(1500,function(){
console.log('1');
}
def();
}
function def(){
console.log('2'}
}
I want 2 to be printed after 1 - how do I do that?
If you want a function to also be called after a delay... just put it inside the delay. I've added some extra console logs and fixed some of your code. Run the below example to see how it works.
function def() {
console.log('2 - def()');
}
function abc() {
console.log('before');
setTimeout(function() {
console.log('1');
def();
}, 1500);
console.log('after');
}
abc();
function abc(def){
setTimeout(1500,function(){
console.log('1');
def();
}
}
You can use async and await. Wrap the setTimeout(...) in a Promise and resolve Promise inside the callback passed to setTimeout.
async function abc(def){
await new Promise(res => {
setTimeout(function(){
console.log('1');
res();
},1500)
})
def();
}
function def(){
console.log('2')
}
abc(def)
setTimeout(function, milliseconds) takes a function has the first parameter and delay value (time in milliseconds) as the second parameter. You were passing them in the wrong order.
Also in your example def() was printing 2 and it was outside the setTimeout function, so it could not have possibly printed 2 after 1 (as 1 was being logged inside the setTimeout, which means it would be executed after the delay of 1.5 seconds).
The solution provided by Chris above is correct and would do what you wanted (print 2 and then 1)

JavaScript CallBack Function ..ish issue

So I was doing some practice about callback function and I wanted to try it out in my own was and use it with a setTimeout Method and to my surprise, it didn't work as expected.. Pls what am i doing wrong here.
function first(number, callback) {
setTimeout(function() {
console.log(number);
}, 5);
callback();
}
function second() {
console.log(2);
}
first(1, second);
You're executing setTimeout and callback at the same time. Because JavaScript is single-threaded, it doesn't wait for setTimeout to complete before executing the next statement.
That's why, 2 prints immediately, and then 1 prints after a delay of 5 milliseconds.
If you want to print 1 first, then you need to call the callback function in the callback of setTimeout. This ensures that the console.log(number) executes prior to calling the callback (which prints 2).
function first(number, callback) {
setTimeout(function() {
console.log(number);
callback();
}, 5);
}
function second() {
console.log(2);
}
first(1, second);
As 31piy already said, setTimeout() and callback() are being executed at the same time. Your code first schedules a function execution at 5ms from now, and then immediately runs another function that logs 2 to the console.
You can achieve the expected result in a couple of similar ways, I'll show one:
function first(number,callback) {
setTimeout(function() {
callback();
}, 5);
console.log(number);
}
function second() {
console.log(2);
}
first(1, second);
//Here, you immediately print the number 1 and schedule the number 2.

jquery delay between javascript functions

I have multiply functions with parameters simplified as:
function f1(p1,p2){
alert('Function one is P1:'+p1+' P2:'+p2);
}
function f2(p1,p2){
alert('Function two is P1:'+p1+' P2:'+p2);
}
I need to fire these is a sequence with a delay between. I have however found that jQuery dislikes running functions with parameters. I have tried the .click function.
$.delay(1000).click(f1('One',false)).delay(1000).click(f2('One',false));
But the delay makes the click functions not work...
I would just use a simple timeout:
f1("one", false);
setTimeout(function() { f2("one", false); }, 1000);
$.delay(1000).click(function(){f1('One',false);}).delay(1000).click(function(){f2('One',false);});
not sure what the click is for though ...
if you want to delay a function call then a much simpler way is to use setTimeout().
eg:
// calling it in a nested setTimeout for sequential delayed execution
setTimeout(function(){
f1('One',false);
setTimeout(function(){
f1('One',false)
},300)
},300)
function fn1()
{
alert(1);
}
function fn2()
{
alert(2);
}
var arr=[fn1,fn2];
var len=arr.length;
var time=1000;
for(var k=0;k<len;k++)
{
(function(k)
{
setTimeout(arr[k],time);
}(k))
time=time*2;
}
It executes after a delay of 1 second!
DEMO

Inner function calling parent function with setTimeout

How can an inner function call a parent function after it has expired?
setTimeout(main, 2000);
function main(){
/* .... code */
setTimeout(console.log("hello after 5 seconds"), 5000);
}
The intended action is to print hello after 5 seconds in 5 seconds (7 total); with the above code it prints it in 2 seconds.
You need to pass setTimeout function references. With setTimeout(console.log("hello after 5 seconds"), 5000);, you call console.log immediately. Any time you write () after a function name, you're invoking it.
console.log returns undefined, which is what is passed to setTimeout. It just ignores the undefined value and does nothing. (And it doesn't throw any errors.)
If you need to pass parameters to your callback function, there are a few different ways to go.
Anonymous function:
setTimeout(function() {
console.log('...');
}, 5000);
Return a function:
function logger(msg) {
return function() {
console.log(msg);
}
}
// now, whenever you need to do a setTimeout...
setTimeout(logger('...'), 5000);
This works because invoking logger simply returns a new anonymous function that closes over msg. The returned function is what is actually passed to setTimeout, and when the callback is fired, it has access to msg via the closure.
I think I understood what you want. Take a look:
var main = function(){
console.log("foo");
var function1 = function( string ) {
console.log("function1: " + string);
};
var function2 = function() {
console.log( "hadouken!" );
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
Or:
function main(){
console.log("foo");
function function1( string ) {
console.log("function1: " + string);
};
function function2() {
console.log( "hadouken!" );
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
I usually prefer the first sintax.
jsFiddle: http://jsfiddle.net/davidbuzatto/65VsV/
It works! You miss word function.
setTimeout(main, 1000);
function main() {
function function1 () { alert(1); };
setTimeout(function1, 1000);
}​

how to do a jQuery timeout

using jQuery... how do I run a function and then run a second function every 2 minutes after.
eg:
function 1: runs once
function 2: runs every 2 minutes after function 1 has finished
Any help will be much appreciated.
C
function f2(){}
function f1(){
... some code ...
setInterval(f2, 2000*60);
}
//From somewhere in your code, call f1
f1();
setInterval also returns a handle which can be used to cancel further calling of that function.
jQuery's delay() function is not a replacement for javascript's setInterval or setTimeout. To run a function #1 once on page load and then function #2 every 2 minutes after:
function funcOne() {
// some javascript
setInterval('funcTwo()', 1000*60*2);
};
function funcTwo() {
// some other javascript
};
$(document).ready(function() {
funcOne();
});
Remember, you are using JQuery because it makes javascript more simple. JQuery is a javascript library, not a language, wich means you can perfectly use javascript functions on it.
For your problem, you only need to call, with the setTimeout, your second function, and put inside this function another setTimeout(ms);
Like this:
function f1(/*...*/){}
var t = setTimeout("f2()",2 * 60 * 1000);
And at the end of your f2() function you should include another setTimeout, in order to call that function every 2 minutes.
function f2(/*...*/){
//...
t = setTimeout("f2()",2 * 60 * 1000);
}
To cancel this callings to f2() is just as simple: clearTimeout(t);
I would rather use setTimeout(). It is supposed to be less demanding on the browser, more processor efficient.
Here's what your functions should look like:
function f2(){
t = setTimeout(f2, 2000 * 60);
// code for f2
}
function f1(){
// code for f1
setTimeout(f2, 2000 * 60);
}
Then wherever it is you want the whole thing to start, call the first function:
var t;
f1();
You can stop the loop anytime:
clearTimeout(t);
Be sure to trigger setTimeout at the beginning of f2, so that it fires exactly every 2 minutes. Any code before 'setTimeout', taking 'x' time to process would result in the next f2 call firing after 2min+x.
Heloo
if i get you right then this is a solution
function func1()
{}
function func2()
{}
window.onload = function()
{
func1();
var flag_first_call_is_after_2=0;
var interv = setInterval(
function()
{
if(flag_first_call_is_after_2==0)
{
flag_first_call_is_after_2=1;
}
else
{
func2();
}
}
,120000
);
}

Categories