Why Is My Function Call That Should Be Scheduled by Settimeout Executed Immediately

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.

Why is setTimeout executing immediately?

because you're actually calling the timeup(tc,chosen) function inside the setTimeout function.

try:

setTimeout(function(){
timeup(tc,chosen);
}, 10000);

setTimeout -- callback executed immediately?

Several problems.

This invokes hide_info right away. Parenthesis invoke a function-object! (or are used for applying precedence to expressions).

That is,

this.id = setTimeout(this.hide_info(), 7000);

Is [mostly] equivalent to:

var temp = this.hide_info()       // call function ... uh, what?
this.id = setTimeout(temp, 7000) // temp is "return" value ("undefined" here)

Oops! That's not right :) So take away the parenthesis. This will pass the function-object itself to the setTimeout. (Yes, functions are just objects in JavaScript. The expression this.hide_info is first evaluated to a function-object and, if there is a (...) after, it will invoke said function-object.)

this.id = setTimeout(this.hide_info, 7000)

However, it is still not correct because this inside the timeout function (hide_info) will be wrong! But this can be fixed with using a closure. (There are many great SO answers on the topic, feel free to search!)

var self = this
this.id = setTimeout(function () {
// now in hide_info "this" will be "self", which was "this" ... outside :)
self.hide_info()
}, 7000)

(Or use Function.bind from ECMAScript ed5 or a library.)

Additionally, this.id is not the same as this.timeoutID, and is suspect for "correctness".

Keep it simple. It's okay to pass undefined/0 to clearTimeout: it'll silently ignore you.

cancel : function () {
clearTimeout(this.id) // but id is a horrid overloaded name :)
this.id = undefined
}

Happy coding.

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

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

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

setTimeout firing function straight away and not waiting

Your function getNegativeErrs() is executing right away and is using its return value as the callback.

The right way:

window.setTimeout(function() {
getNegativeErrs(errors)
}, 5000);

function getNegativeErrs(ers) {
for( i in errors ) {
var errobj = getByValue(dataLayer, errors[i]);
if(!errobj) {
dataLayer.push({
'event': 'negative_errors',
'unseen': errors[i],
'module': 'registration'
})
}
}
}


Related Topics



Leave a reply



Submit