This question already has answers here:
setTimeout ignores timeout? (Fires immediately) [duplicate]
(3 answers)
Closed 8 years ago.
I'm working on a Chrome extension to fetch tweets and I figured that I could use the setInterval() function to make the script run every minute. First I tried giving it the function like this:
setInterval(myFunction(), interval);
But it would only execute my script once.
Then out of curiosity I tried declaring the function in the setInterval() function like so:
setInterval(function() {body of my function}, interval);
And that works, but is not a very pretty solution, does anybody any other way of doing this or am I just going to have to deal with it?
Just remove the brackets from the first call. The reason for this is that you need to pass in the function, not the result of the function (what it returns).
When you write the function's name with brackets, it calls the function. When you exclude the brackets, it simply refers to the function like a variable, and so you can pass in your function to the setInterval() function.
setInterval(myFunction, interval);
Related
This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 4 years ago.
I am using the below code to play an audio file for every second, the audio file is a second long and it basically a tick. The code will run only once and then I see the error in the console. My intention is to make it run every second until something is achieve then I can clear the Interval. This is the error I am getting in the console
Uncaught SyntaxError: Unexpected identifier
setInterval (async)
This is my code:
$('select[name=notsound]').change(function(){
var h = $(this).val();
var tickAudio = new Audio('https://www.sample.com/sounds/'+h+'');
setInterval(tickAudio.play(),1000);
});
I am not sure why is this happening, I am sure that I have made some error which is causing this issue, as it was working before I thought of giving it a different approach. Thank you for reading my query. :)
Method play needs to be called in the context of the right object:
var cleartick = setInterval(tickAudio.play.bind(tickAudio),1000);
The second suggestion of #rmlan will also work.
Clearing interval is the same - you need not to call a function, but to pass a function reference to setTimeout:
setTimeout(clearInterval, 3000, cleartick);
setInterval/setTimeout have a convenient way of passing parameters to timer functions - as cleartick above.
You are currently "executing" the result of tickAudio.play() every second, instead of executing the function itself.
To remedy this, you can either pass the function as an object:
setInterval(tickAudio.play.bind(tickAudio),1000);
Or wrap the call in an anonymous function:
setInterval(function () { tickAudio.play() },1000);
This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 5 years ago.
I'm currently a teacher's assistant in a web development course. Today, a student asked for help with his homework, in which he'd used setInterval, passing as the first parameter a function which he didn't define until a few lines of code later. I told him that wouldn't work, as the function would be undefined by the time the interval setting code was reached.
To my surprise, it worked perfectly. I've been trying to research this and am coming up blank: does JavaScript actually wait until the first execution of the callback to even see if the function name passed to it exists? That seems so counter-intuitive, but I can't imagine any other reason it would have worked. Where can I find out more about this unexpected behavior?
It depends:
If its a function expression :
//callback not defined ( exists but undefined)
var callback=function(){};
//callback defined
If its a function declaration :
//callback is defined
function callback(){}
//callback is defined
This is called hoisting, so vars and functions are moved to the top.
It also depends on the passed function too:
setInterval(callback,0);//doesnt work, callback is *undefined* in this moment
setInterval(function(){ callback();},100);//does work as callback is just called before being referenced.
var callback=function(){};
This question already has answers here:
When to use () after a callback function name? [duplicate]
(5 answers)
Closed 6 years ago.
Well I'm starting with jQuery and I'm wondering what is the difference between writing a function with or without parentheses inside a function.
For example if I have the following function:
function test(){
alert("pen pineapple apple pen");
}
This:
$(document).ready(test);
and this:
$(document).ready(test());
both show the same result: "pen pineapple apple pen"
Putting parentheses () at the end of a function causes that function to be invoked immediately, and use its return value in the expression.
This code $(document).ready(test); is using test as a callback function. It essentially says: when the document becomes ready, call the function that I'm providing you with (test).
This code $(document).ready(test()); is immediately invoking the function test, having it return a value, and then passing that value to the ready method. It's possible that test is returning a different function here, which in turn will act as the required callback function. It could also just be an error though, with someone inadvertently including the parentheses when they shouldn't have.
This question already has answers here:
JavaScript - SetInterval doesn't function properly
(4 answers)
Closed 6 years ago.
I have a class named main with a method called setDate(). In the constructor method I put the line: setInterval(main.setDate(), 10000) and it only runs the initial time the object is instatiated. If I put the line as a tail call in the setDate() method, it runs infinitely & breaks the browser session.
Try to pass the function reference,
setInterval(main.setDate, 10000);
You are calling it. So that function will be called and its returning value will be passed as the first parameter to setInterval.
You could also achieve the required effect by passing the function call as a string,
setInterval("main.setDate()", 10000);
But passing string is not recommended as it would be evaluated under the hood in window scope.
This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
JS setInterval executes only once
(2 answers)
Closed 6 months ago.
Just as the title says: setInterval is only firing its callback once.
manifest.json:
{
//...
"content_scripts" : [{
"js" : ["code.js"],
//...
}],
//...
}
code.js (example):
setInterval(alert('only shown once'),2000);
Why, and how I could fix it? The code works well outside of an extension (even in a bookmarklet).
setInterval(function() { alert('only shown once') },2000);
You need to pass a function reference like alert and not a return value alert()
setInterval isn't working at all.
The first argument should be a function, you are passing it the return value of alert() which isn't a function.
Use the three argument version:
setInterval(function,time,array_of_arguments_to_call_function_with);
setInterval(alert,2000,['only shown once']);
The way you wrote it it's wrong:
setInterval() wants a function and a numerical value: setInterval(function(){//your code}, timeInterval).