Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  96] [ 3]  / answers: 1 / hits: 157535  / 15 Years ago, wed, september 30, 2009, 12:00:00

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.


More From » jquery

 Answers
4

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.


[#98591] Friday, September 25, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maleahp

Total Points: 223
Total Questions: 102
Total Answers: 116

Location: Sao Tome and Principe
Member since Wed, Dec 29, 2021
2 Years ago
;