Why setTimeout() function runs only once? - javascript

I am making a javascript bookmarklet that resizes all images, periodically.
javascript: function x(){
for(i=0;i<=document.getElementsByTagName('img').length;i++)
document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);
But it runs only once. What is the problem here??

Are you looking for setInterval() instead of setTimeout() by any chance?
t = window.setInterval("x()",100);

Here is the same code properly indented for clarity
function x() {
for(i=0;i<=document.getElementsByTagName('img').length;++)
document.getElementsByTagName('img')[i].width+=1;
};
t = window.setTimeout("x()",100);
void(0);
window.setTimout() executes the passed code only once because it is meant to. If you want to execute code more often, use window.setInterval().

Shouldn't it be i++ at the end of your for loop?

Also there is a syntax error.
for(i=0;i<=document.getElementsByTagName('img').length;i++)

You need to put the...
t = window.setTimeout("x()",100);
inside the function x() brackets { } and it works with SetTimeout()
function x() {
for(i=0;i<=document.getElementsByTagName('img').length;i++)
document.getElementsByTagName('img')[i].width+=1;
t = window.setTimeout("x()",100);
};
x();
void(0);
You can only call x() after all the images have been loaded on the page or there is an error.

It might be window.setTimeOut("x",100)
Edit : correct the answer to this window.setTimeout(x,100).
PS: thats what happens if you simply work with a IDEs.

Related

Anonymous JavaScript function not executing

I could really use a second pair of eyes on this. I get the following error:
"Uncaught TypeError: undefined is not a function"
Can anyone see what is wrong with this function because I can't seem to debug
$(function(){
$('#div-id').insertBefore('#sumbit-button');
})();
jQuery already executes the function you pass to it, it does not return a function so you can't call it.
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
There's 2 different things you can mean with this code. Either you're trying to make a function run on DOM ready, which would use the jQuery code:
$(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
});
Which is also what aduch said, but you can also be referring to a self-executing anonymous function, which would be this vanilla JS code:
(function(){
$('#UGInterestedIn').insertBefore('#sumbit-button');
})();
The difference is that the first code requires jQuery to be included on the page, and loads the code when the DOM is ready. The second code runs the code immediately, but uses the anonymous function to change the scope of the variables. You're probably trying to do the first thing, but I thought I'd let you know about the second one too.

setInterval function not working

I seem to not be able to call the setInterval function like this:
this.timerHandler = setInterval(function(this.myTimerFunction){},1000)
It seems that if I make a global function and call that, the code works perfectly but it seems that calling a function locally using this, it won't work. I have tried calling this.myTimerFunction just before this line of code and it actually executes the code and works perfect, it's just that it seems it does not want to execute the function from a timer handler.
Any suggestions to try and fix this? this.myTimerFunction is a prototype function btw.
the syntax is wrong, you also have to take into account the context
var that=this; //save context
this.timerHandler = setInterval(function(){ //You can not use "this." like parameter
that.myTimerFunction(params);
},1000)
if you don't need send parameters in your function you can use
this.timerHandler = setInterval(this.myTimerFunction,1000);
setInterval takes a function and an interval.
function(this.myTimerFunction){}
should just be:
this.myTimerFunction
or
this.myTimerFunction.bind(this)
You may not need the bind if the context doesn't matter.
Try this:
this.timerHandler = setInterval(this.myTimerFunction, 1000);

setInverval cannot find function?

I dumbed down this script so it wasn't so bulky, but the gist of it is that I keep getting a reference error every second that I have no function getList(). I tried to move setInverval() above and below it but it pretty much does nothing. It tells me an anonymous function is calling getList and that it is not defined.
If it makes a difference I had to add the jquery conflict so that it didn't interfere with mootools and I'm running joomla 1.5
jQuery(document).ready(function($) {
function getList(){
i=0;
$.getJSON(
"./test.php",
function(data)
{
while(data.streams[i]){
channel[i] = data.streams[i];
stats[i] = data.status[i];
title[i] = data.title[i];
viewers[i] = data.viewers[i];
i++;
}
}
);
}
setInterval("getList()", 1000);
});
I tried debugging it via console, but I'm still new at console debugging so it didn't get me too far. This program works alone, without joomla and the jquery no conflict stuff, in it's on HTML file just fine so I'm not sure what could possibly be wrong :/
When using the eval-style version of setInterval() (by passing a string) the function must be global. This is a bad thing anyway, so do this instead:
setInterval(getList, 1000);
And so you never pass a string again, in case you need arguments, do it like this:
setInterval(function() {
getList(whatever, ...);
// you can have more code here and even access local variables
}, 1000);
setInterval(getList, 1000);
setInterval (as well as setTimeout) require a reference to a function. Passing the function as strings have the same risk as using eval
Passing a string instead of a function to setTimeout() suffers from the same hazards as using eval. String literals are evaluated in the global context, so local symbols in the context where setTimeout() was called will not be available when the string is evaluated as code.

Why isn't this setInterval working?

The code:
setInterval("doSomething()", 2000);
function doSomething(){alert('hi')}
demo: http://jsfiddle.net/PRff7/
I've been reading about this and I just can't get the example to work :(
Your code isn't executing because of jsfiddle. It wrapped your code in an onload handler, thus keeping doSomething out of the global namespace. So when setTimeout tried to execute your code, it couldn't find doSomething. Change jsfiddle to execute "no wrap", and all is well: http://jsfiddle.net/gilly3/PRff7/3/
If you don't wrap your call to doSomething in a string, it will also work because setInterval gets a direct reference to doSomething which is in the same scope. It doesn't need a global reference.
You need to change it to
setInterval(doSomething, 2000);
function doSomething(){alert('hi')}
You shouldn't pass a string to setInterval.
Instead, pass the function itself:
setInterval(doSomething, 1000);
If you want to leave your code inline, and not to delegate it to some named function (especially if code consists of more than one command), use this:
setInterval( function(){ alert('hi'); alert('hello') }, 2000);

Self invoking functions javascript

I wrote a self invoking function in both firefox and chrome it it wouldn't invoke.
I wrote something to the effect of
(function () { alert("THE"); })();
do self invoking functions not work in current browsers?
I did include all essential tags and all other code works on the page
"Self-invoking functions" are not really a part of javascript, it's just a term that people are calling a specific pattern of code (like AJAX, etc.); these patterns should work anywhere that javascript works.
What you're calling a "self-invoking function" is just creating an anonymous function and immediately calling it (as opposed to say storing it in a var, as an object value, as a function param, etc.).
That is, the following are basically the same:
var f = function(){...}; f()
and
( function(){...} )()
So because your 'self-invoking function' is a basic part of javascript, there is no possible way it's not working unless the insides aren't working or your environment is messed up. You could copy-paste your code onto a new blank page, and it would work fine. Something else must be going wrong:
Check your errors in your dev console. Specifically, check to make sure you don't have a syntax error or that there isn't some weird thing going on with the webpage you're testing it on (e.g. if you somehow redefine alert...).
I had this issue with a self invoking function which produced this error...
Uncaught TypeError: object is not a function
The problem was caused by not having a semi colon ending the line before the opening bracket
That function works. Javascript supports functional programming, so for a browser not to run that code, even for a very old browser that would be absurd. Are you sure that statement is being reached? Try debugging javascript that occurs before that statement.
<script type="text/javascript">
(function() {
alert('Hello World!');
})();
</script>
Works in every browser I have installed on this machine.
This function definitely works. I would check your browser's console for any js errors in your page. Perhaps you could try to put a simple console.log function at the beginning of your script to see if any JavaScript is being called in the first place.
This self invoking function with return value will work in all current browsers(Safari, Chrome and Firefox) without issue. This function executes immediately, automatically and anonymously.
<script type="text/javascript">
alert((function(){
return("Hello World");
})());
</script>
I had a similar problem. I'm mentioning it below.
I couldn't run this self-invoking function on any browser
(function myfunc() {
var x = 34;
console.log(x);
})();
but whenever I added window.onload like below, it worked fine:
window.onload = (function myfunc() {
var x = 34;
console.log(x);
})();

Categories

Resources