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);
Related
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);
I see
First
$(function() {
...
});
Second
(function() {
})();
Third
function() {
}
$(document).ready(function(){
});
Maybe there are more, what are the differences?
Your notation is mainly jQuery (atleast the ones with $)
This is shorthand for a DOM ready function, equivalent to the bottom one
This is a self executing function with the parameter specified in the trailing ()
This is a DOM ready function $(document).ready(function() {}); atleast, the function above it is simply a function.
so these indeed are a few different ways to execute javascript code, some of them are library dependent (using jQuery) others are done specifically because of differences in scope.
the first block:
$(function() {
...
});
is utilizing the js library jQuery that uses the namespace '$' what you are doing here is calling the jQuery '$' function passing in the first parameter of another anonymous function... this is a shorthand way to call $(document).ready(function(){});... both of those statements wait for the DOM to complete loading (via the onload event) before interpreting the javascript inside
the second block:
(function() {
})();
is a procedure called an (IIFE) Immediately-Invoked Function Expression... which in essense is defining an anonymous function and calling it immediately.
the third block:
function() {
}
$(document).ready(function(){
});
represents two things... the first function declared actually should have been named something like function myFunction(){...} and thus could be called later myFunction(parameters);
and finally $(document).ready(function(){}); is the javascript library jQuery's way of saying grab the 'document' element of the dom, and attach an event listen to it looking for the onload event, when that event is triggered execution the function passed as a parameter...
$(document).ready(function () {
function EndSession() {
window.close();
};
setTimeout("EndSession()", 10000);
});
Shown above is the code in a child page opened using window.open().
The problem is after ten seconds when it tries to call EndSession, it throws an error
"Microsoft JScript runtime error: 'EndSession' is undefined"
What is going on here?
Maybe the problem of the old way "string" is that it was looking for the method in the global scope, while the method was defined inside the function used for jQuery ready.
We can explicitly pass the function we really want to, if we have a proper reference to it.
Let's try:
$(document).ready(function () {
var endSession = function() {
window.close();
};
setTimeout(endSession, 10000);
});
Although I haven't tried it, maybe even this will work:
$(document).ready(function () {
setTimeout(window.close, 10000);
});
I'm not sure if you need the jQuery ready at all too, unless you intentionally want to start counting time after the document is fully loaded (which I'd expect to be very quick for a pop-up that closes soon).
When the timeout event triggers, the code you specified is run in the global namespace.
Your code is "EndSession()", so the browser tries to find a global function with the name EndSession. There is no such function, because you defined EndSession() inside an anonymous function that you passed to $(document).ready().
So, defining EndSession as global will suffice.
function EndSession() {
window.close();
};
$(document).ready(function () {
setTimeout("EndSession()", 10000);
});
Also, functions that are not constructors should, by convention, start with lowercase letter ;)
that should be like this,
setTimeout(EndSession, 10000);
DEMO
<!doctype html>
<html>
<body>
<div id = 'div' style = 'width:100px;height:100px;background:#000000;'></div>
<script type = 'text/javascript'>
document.getElementById('div').addEventListener('click',happen(),true);
function happen()
{
alert(1)
}
</script>
</body>
</html>
In the above code why the event is triggered when the page loads and not triggered when i click on the div...Also which is the correct event name click or onclick....
It's because you've immediately called the function, and passed its null result to addEventListener().
It should be:
document.getElementById('div').addEventListener('click',happen,true);
If you want to pass arguments to happen, you'd have to write this:
document.getElementById('div').addEventListener('click', function() {
happen(args_here, ...);
}, true);
You're calling the function immediately and passing its return value to addEventListener, just like any other function call.
Take out the ().
This should work:
document.getElementById('div').addEventListener('click',happen,true);
The problem is with this line:
document.getElementById('div').addEventListener('click',happen(),true);
You should should only be passing the name of the function happen but since you added the parentheses, you are passing the result.
Try this instead:
document.getElementById('div').addEventListener('click',happen,true);
As the other answerers have said, taking out the () will fix the problem.
An alternative, and a good practice for OO Javascript, is to wrap the function inside a function(){ }, like so:
document.getElementById('div').addEventListener('click',function(){happen()},true);
That will retain scope if the callback needs to execute within an object (in this case it does not).
The event handler does not need parenthesis
document.getElementById('div1').addEventListener('click',happen,true);
I'm still new to JQuery, on the way to getting my ajax example to work i got stalled with setTimeout. I have broken it down to to where it should add "." to the div every second.
The relevant code is in two files.
index.html
<html><head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript' src='myCode.js'></script>
</head>
<body>
<div id='board'>Text</div>
</body>
</html>
and myCode.js
(function(){
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
})();
the myCode.js file works alright and "update()" runs the first time through but never again.
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update() within the code block is within scope now.
I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
setInterval(function() {
$('#board').append('.');
}, 1000);
You can use clearInterval if you wanted to stop it at one point.
SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.
This accomplishes the same thing but is much simpler:
$(document).ready(function() {
$("#board").delay(1000).append(".");
});
You can chain a delay before almost any jQuery method.