I have a question about javascript function sequence,I have two code below,Why the different results of these two programs?
I think first program result will equal to second program result.
function test1() {
for (var i = 1; i <= 1000000; i++) {
}
console.log("test1");
}
function test2() {
console.log("test2");
}
test1();
test2();
//test1
//test2
function test1() {
setTimeout(function() {
console.log("test1");
}, 1000);
}
function test2() {
console.log("test2");
}
test1();
test2();
//test2
//test1
Because the purpose of setTimeout (MDN | spec) is to schedule a call to a function later, asynchronously. So in your second example, you call test1 first, and it schedules a call to the anonymous callback for a second later, then returns. Then you call test2 which prints immediately. A second later, the callback is called by the timer, and prints test1.
Perhaps this small tweak to your second example will make it clearer:
function test1() {
console.log("test1 called, setting up timer");
setTimeout(function() {
console.log("timer fired and called the callback");
}, 1000);
}
function test2() {
console.log("test2 called");
}
test1();
test2();
You see this output (the last line only appears after a second):
test1 called, setting up timer
test2 called
timer fired and called the callback
setTimeout is an asynchronous operation , the number is use to define delay at which the code will execute. 1000 is the delay, so you are seeing the result differently
http://javascript.info/tutorial/settimeout-setinterval
check this out
mabe it will help :)
In my opinion, maybe your current thread got stuck in the "for" loop in your first code snippet. But the operation is asynchronously done in the second code snippet.
Related
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)
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.
I was reading one book named 'Hands on node.js' by 'Pedro Teixiera'.
I was trying to execute one same program giving in that book that will call a function and that function is calling the same function recursively within some interval again and again.
But when I executed, it gives only one time '1' and stops
Please help me to figure it out why it is not able to call the same function again.
Sample program is as follows:
var schedule = function(timeout, callbackfunction) {
return {
start: function() {
setTimeout(callbackfunction, timeout)
}
};
};
(function()
{
var timeout = 10000; // 1 second
var count = 0;
schedule(timeout, function doStuff() {
console.log(++ count);
schedule(timeout, doStuff);
}).start(timeout);
})();
You aren't actually calling the function again. start() is the part that starts the timer.
schedule( timeout, function doStuff() {
console.log( ++count );
schedule( timeout, doStuff ).start(); // <--- added .start() here
}).start();
(Also note that the start() function doesn't take parameters.)
with some interval again and again
No, for that you would have used setInterval instead of setTimeout.
it gives only one time '1' and stops
Yes, your doStuff function doesn't put a new timeout. Your odd schedule function needs to be .start()ed!
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
);
}
I have two asynchronous objects fn1 and fn2 and sometimes I want to run them synchronously.
For simplicity I wrote the code in this way:
var fn1 = function () {
setTimeout(function () {
console.log("fn1");
},200);
};
var fn2 = function () {
setTimeout(function () {
console.log("fn2");
},100);
};
fn1();
fn2();
but let's suppose is not possible to modify the fn1 and fn2 object.
What is the best way to run fn2 only when fn1 has finished to be executed?
If you want to execute f1() when f2() has finished, use the method as described and shown below.
Create a poller function, which checks for variable/property changes created by method fn2. Example:
function fn1(){/*...*/}
function fn2(){
//Lots of code, including:
window.someDynamicVar = "SPECIAL_token"; //Unique, only defined by this func
}
(function(){//Anonymous wrapper, don't leak variables
var timer = window.setInterval(function(){
//check whether an unique environment change has been made by fn2():
if(window.someDynamicvar == "SPECIAL_token"){
clearInterval(timer); //Clear the poller
fn1(); //Call fn1
}
}, 200); //Poller interval 200ms
})();
The concept behind this code is that the fn2() function changes variables during/after execution, which can be read. When such a change has been detected, the poller is cleared, and fn1() is executed.
"...let's suppose is not possible to modify the fn1 and fn2 object."
Without modification, they will behave as asynchronous functions are meant to behave; they will run asynchronously.
If you have foreknowledge of the duration in the first function, you could delay the execution of the second by the same duration.
f1();
setTimeout(f2,200);
You should use a callback function.
http://recurial.com/programming/understanding-callback-functions-in-javascript/
var fn2 = function (myCallback) {
setTimeout(function () {
console.log("fn2");
myCallback();
},100); };
In the general case, there isn't a pretty way. Are you sure you can't change teh functions so they receive continuation functions to call when they are done?
function f1(continuation){
setTimeout(function(){
console.log("f1");
continuation(); //kind of like a return...
}, 100);
}
function f2(continuation){
setTimeout(function(){
console.log("f2");
continuation();
}, 100);
}
f1(function(){
f2( function(){
console.log("this runs after f2 ends");
})
})
fn1 and fn2 are most certainly objects, contrary to what is said below (or above), but that's a different story. The easiest way to do what you want to, it to provide an optional callback parameter.
var fn1 = function (callback) {
setTimeout(function () {
console.log("fn1");
if (callback) callback();
},200);
};
var fn2 = function (callback) {
setTimeout(function () {
console.log("fn2");
if (callback) callback();
},100);
};
So instead of:
fn1();
fn2();
You would do:
fn1(fn2);
or to be explicit about it:
fn1(function() {
fn2();
});
fn1 and fn2 are not objects
Read up about setTimeout. Get fn1 to call fn2 when it is done