Settimeout Calls Function Immediately Instead of After Delay

setTimeout calls function immediately instead of after delay

A function object in JavaScript is one thing. A function call is a different thing. You're using the latter, by including parentheses after the function name*, but you need the former, without parentheses. This allows setTimeout to later invoke the function itself by using the passed-in object. Assuming you do actually want 5 seconds (rather than the 50 seconds the original code was using):

setTimeout(GetUsersNumber, 5000);

*Really, any old variable that holds a function object can be invoked like that, but for convenience, defining a function also defines a variable name for it.

How to execute setTimeout function immediately after the delay?

I thought I would mention that if those test() calls do not perform DOM operations you could possibly move them to a worker.

Web Workers allow running code on a background thread that doesn't block your main UI thread.
I've created a quick example that runs a synchronous task of arbitrary duration on a worker thread. On the main thread setInterval and setTimeout calls are running uninterrupted.

See it in action.

index.js

let interval = setInterval(() => console.log("Not blocked"), 500);

console.log("Scheduling to run in 2 seconds");
setTimeout(() => {
console.log("2 seconds passed. Running scheduled task! ");
}, 2000);

let longTaskRunner = new Worker("./src/worker.js");
let taskDuration = 3;
console.log(
`Starting synchronous task that takes more than ${taskDuration} seconds`
);

longTaskRunner.postMessage(taskDuration);
longTaskRunner.onmessage = function(e) {
console.log(`Long task completed in ${e.data} seconds`);
clearInterval(interval);
};
longTaskRunner.onerror = function(e) {
console.log(e.message);
};

worker.js

self.onmessage = function(e) {
const runFor = e.data * 1000;
let startedAt = Date.now();
let timeElapsed = 0;

while (timeElapsed < runFor) {
timeElapsed = Date.now() - startedAt;
}

self.postMessage(timeElapsed / 1000);
};

Why is the method executed immediately when I use setTimeout?

You're calling the function immediately and scheduling its return value.

Use:

setTimeout(testFunction, 2000);
^

Notice: no parens.

setTimeout() executing function immediately without delay

setTimeout takes as the first parameter a function, alice.sayHi.call(bob) is not a function, it's undefined (it is the returned value of the function, not the actual function).

So you need to specify a callback instead, wrap your function inside another one like so:

var name = "Window";

var alice = {

name: "Alice",

sayHi: function() {

console.log(this.name + " says hi");

}

};

var bob = { name: "Bob" };

setTimeout(() => {

alice.sayHi.call(bob)

}, 1000);

Is setTimeout with no delay the same as executing the function instantly?

It won't necessarily run right away, neither will explicitly setting the delay to 0. The reason is that setTimeout removes the function from the execution queue and it will only be invoked after JavaScript has finished with the current execution queue.

console.log(1);
setTimeout(function() {console.log(2)});
console.log(3);
console.log(4);
console.log(5);
//console logs 1,3,4,5,2

for more details see http://javascriptweblog.wordpress.com/2010/06/28/understanding-javascript-timers/

setTimeout runs immediately

That is because you are calling the function "function(elem)" instead of providing it as an arguement. Try this

(function ($) {
$.fn.enable = function (delay) {
console.log(delay); //logs 3000
var elem = this;
setTimeout(function () {
console.log(elem);
elem.css("opacity", "1");
}, delay); //you should not call a function here
return this;
};
})(jQuery);


Related Topics



Leave a reply



Submit