setInterval() will not run immediately [duplicate] - javascript

I found a solution to run interval in javascript immidiately, not waiting for a first "timeout"
setInterval(function hello() {
console.log('world');
return hello;
}(), 2500);
But problem is this solution isn't working is construction like this
(function () {
window.Banner = {
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}, 2500);
}
}
})();
Banner.doMagic();
I've tried to return Banner method, to name it and return and no success.
Point is what in real construction is much more complex, so i can't just rewrite it to "return setTimeout" solution, as offered widely, so it would be really perfect to find what am i doing wrong with this one.
http://jsfiddle.net/5jawxLnr/3/

Perhaps the most proper way to do it would be to take the whole callback outside of the setInterval call and put it in a separate variable:
(function () {
window.Banner = {
doMagic: function () {
var magic = function() {
console.log('magic');
};
setInterval(magic, 2500);
magic();
}
}
})();
Banner.doMagic();
The effect is the same as your first code, but this way your code is a little cleaner.

Your no longer self-executing the function in your 2nd code snippet. You need to change this to the following:
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}(), 2500);
}
I agree with others though, this isn't the cleanest way to do this and isn't very obvious to the next developer who comes along. I recommend storing the function in a variable, executing it immediately and then running it in the setInterval also:
doMagic: function () {
var magic = function magic() {
console.log('magic');
return magic;
}
magic();
setInterval(magic, 2500);
}

If you add the parenthesis to the below code part it does
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}(), 2500); // added them here
}

In your code there is no way to perform the required task, instead follow the below approach:
// Use function to perform the task.
function doTask () {
console.log("...");
}
// Perform task for the first time.
doTask();
// On interval do task.
setInterval(doTask, 2500);

Try this example
var hello = function() {
document.write('hello... ');
};
setInterval(hello, 1000);
hello();

Related

How do I call a function inside a struct from that function in node.js?

Okay, this is a basic outline of my code
exports.entity = {
name:"Foo",
//Etc...
start:function() {
this.attack();
},
attack:function() {
setTimeout(attack, 1000); //Doesn't work
setTimeout(this.attack, 1000); //Doesn't work
setTimeout(this, 1000); //Doesn't work
}
}
As you can probably see, I would like to call attack() from inside that function using a setTimeout. Unfortunately, everything I've tried doesn't work, and I'm running dry on ideas. I couldn't find anything on the internet. Does anyone know how I can achieve this?
Note:
When I say doesn't work, I mean that it gives me an error saying something like (insert what I tried here, e.g. 'this.attack') is not a function
What I usually do to avoid problems of scope is to split the functions. And then export the object.
const attack = () => {
console.log('attacking');
setTimeout(() => {
stop();
}, 1000)
};
const stop = () => {
console.log('stopping');
}
const start = () => {
attack();
}
module.exports = { start, stop, attack }
Otherwise you can bind(this) as it was suggested in the comments.
setTimeout has own scope that is why It is overriding this
You can use bind or take variable outside setTimeout
//using bind
setTimeout((function() {
this.attack();
}).bind(this));
//using variable
var context = this;
setTimeout(context.attack, 1000);
It can look like this:
let entity = {};
entity.name = "Foo";
// Etc...
entity.start = function() {
this.attack();
}.bind(entity);
entity.attack = function() {
console.log('attack');
setTimeout(this.attack, 1000); //Doesn't work
}.bind(entity);
exports = { entity };

JavaScript setInterval immediately run

I found a solution to run interval in javascript immidiately, not waiting for a first "timeout"
setInterval(function hello() {
console.log('world');
return hello;
}(), 2500);
But problem is this solution isn't working is construction like this
(function () {
window.Banner = {
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}, 2500);
}
}
})();
Banner.doMagic();
I've tried to return Banner method, to name it and return and no success.
Point is what in real construction is much more complex, so i can't just rewrite it to "return setTimeout" solution, as offered widely, so it would be really perfect to find what am i doing wrong with this one.
http://jsfiddle.net/5jawxLnr/3/
Perhaps the most proper way to do it would be to take the whole callback outside of the setInterval call and put it in a separate variable:
(function () {
window.Banner = {
doMagic: function () {
var magic = function() {
console.log('magic');
};
setInterval(magic, 2500);
magic();
}
}
})();
Banner.doMagic();
The effect is the same as your first code, but this way your code is a little cleaner.
Your no longer self-executing the function in your 2nd code snippet. You need to change this to the following:
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}(), 2500);
}
I agree with others though, this isn't the cleanest way to do this and isn't very obvious to the next developer who comes along. I recommend storing the function in a variable, executing it immediately and then running it in the setInterval also:
doMagic: function () {
var magic = function magic() {
console.log('magic');
return magic;
}
magic();
setInterval(magic, 2500);
}
If you add the parenthesis to the below code part it does
doMagic: function () {
setInterval(function magic() {
console.log('magic');
return magic;
}(), 2500); // added them here
}
In your code there is no way to perform the required task, instead follow the below approach:
// Use function to perform the task.
function doTask () {
console.log("...");
}
// Perform task for the first time.
doTask();
// On interval do task.
setInterval(doTask, 2500);
Try this example
var hello = function() {
document.write('hello... ');
};
setInterval(hello, 1000);
hello();

setTimeout wait for setTimeout

I stumbled upon a problem:
the code is supposed to output "hi1" "hi2" "hi3" "hi4" in that order.
I wrote this simplified code, the actual code is more complicated and causes me to not be able to remove some of the functions I marked.
function test() {
console.log("hi2");
setTimeout(function () { //maybe replace this?
console.log("hi3");
}, 2000);
}
console.log("hi1");
test();
setTimeout(function () { //cannot get rid of this
console.log("hi4");
}, 0);
how do I make it output in order?
If you need to wait for setTimeout in your test() to execute before continuing, the easiest way is to use callback:
function test(callback) {
console.log("hi2");
setTimeout(function () {
console.log("hi3");
// Execute additional logics
callback();
}, 2000);
}
console.log("hi1");
test(function () {
setTimeout(function () {
console.log("hi4");
}, 0);
});
Use the callback or try to show your complicated code is more. We can help you to analyze it.
As others have pointed out setTimeout is asynchronous so they run in the background while the rest of the code continues. I'd guess that at the moment you get something like:
hi1
hi2
hi4
then a 2000ms delay, then
hi3
If you can't change the code much then try changing the delay for hi4 to 4000 like:
setTimeout(function () { //cannot get rid of this
console.log("hi4");
}, 4000);
That should fix the order, but it's still pretty messy and unreliable. I'd rather have something like:
function showMessage(msg, delay) {
setTimeout(function() {
console.log(msg);
}, delay);
}
showMessage('hi1', 0);
showMessage('hi2', 2000);
showMessage('hi3', 4000);
showMessage('hi4', 6000);

Javascript setInterval function to clear itself?

myInterval = setInterval(function(){
MyFunction();
},50);
function MyFunction()
{
//Can I call clearInterval(myInterval); in here?
}
The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks.
EDIT: Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.
As long as you have scope to the saved interval variable, you can cancel it from anywhere.
In an "child" scope:
var myInterval = setInterval(function(){
clearInterval(myInterval);
},50);
In a "sibling" scope:
var myInterval = setInterval(function(){
foo();
},50);
var foo = function () {
clearInterval(myInterval);
};
You could even pass the interval if it would go out of scope:
var someScope = function () {
var myInterval = setInterval(function(){
foo(myInterval);
},50);
};
var foo = function (myInterval) {
clearInterval(myInterval);
};
clearInterval(myInterval);
will do the trick to cancel the Interval whenever you need it.
If you want to immediately cancel after the first call, you should take setTimeout instead. And sure you can call it in the Interval function itself.
var myInterval = setInterval(function() {
if (/* condition here */){
clearInterval(myInterval);
}
}, 50);
see an EXAMPLE here.
var interval = setInterval(function() {
if (condition) clearInterval(interval); // here interval is undefined, but when we call this function it will be defined in this context
}, 50);
Or
var callback = function() { if (condition) clearInterval(interval); }; // here interval is undefined, but when we call this function it will be defined in this context
var interval = setInterval(callback, 50);
From your code what seems you want to do is to run a function and run it again and again until some job is done...
That is actually a task for the setTimeout(), the approach is similar:
var myFunction = function(){
if( stopCondition ) doSomeStuff(); //(do some stuff and don't run it again)
else setTimeout( myFunction, 50 );
}
myFunction(); //immediate first run
Simple as that :)
Of course if you REALLY want to use setInterval for some reason, #jbabey's answer seems to be the best one :)
You can do it by using a trick with window.setTimeout
var Interval = function () {
if (condition) {
//do Stuff
}
else {
window.setTimeout(Interval, 20);
};
};
window.setTimeout(Interval, 20);

SetTimeout Executing faster then assigned interval

I have assigned 5000 ms to Settimeout but it is executing before assigned time interval.Can any body explain why it is happening.
<script type="text/javascript">
var getcallback = {
closure: function (callback, functionparam) {
return callback.call(functionparam);
}
}
var cleartimeout;
var startSlideShow = {
timerid: 5000,
startAnimation: function () {
cleartimeout = setTimeout(getcallback.closure(function () {
alert("this is a basic example of chaining methods");
this.startAnimation();
},this), this.timerid);
},
stopAnimation:function(){
}
}
startSlideShow.startAnimation();
</script>
Because getcallback.closure() is executing the function right away, you are not storing a reference to a function to call at a later time.
As soon as you call startAnimation, you're calling getcallback.closure, which immediately calls the callback function. To use setTimeout correctly, you need to either have closure return a function, or not use such a strange thing, and instead just use an anonymous function.
Something along the lines of:
var getcallback = {
closure: function (callback, functionparam) {
return function() {
callback.call(functionparam);
};
}
}
...
Or, to be cleaner, just:
var cleartimeout;
var startSlideShow = {
timerid: 5000,
startAnimation: function () {
cleartimeout = setTimeout(function () {
alert("this is a basic example of chaining methods");
this.startAnimation();
}, this.timerid);
},
stopAnimation:function(){
}
}
startSlideShow.startAnimation();

Categories