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.
Related
I have a similar question before, my question was about how to access all the JavaScript functions in the web browser console even if they were within window.onload = function() {// code and functions} , but this time I want to do the same thing with jQuery:
$(document).ready(function() {
// I want to access all the functions that are here in the web console
})
You can use the same syntax as in your previous question. Simply assign the function to the window.
The following example illustrates what I mean. Note that you do not need the setTimeout(), this is just for this example here to auto-execute the your_function() when it is defined.
$(document).ready(function() {
window.your_function = function(){
console.log("your function");
};
your_function();
});
// setTimeout() is needed because the $.ready() function was not executed when
// this code block is reached, the function(){your_function();} is needed because
// the your_function() is not defined when the code is reached
setTimeout(function(){
your_function();
}, 500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note 2: I suggenst not to define global functions in the $(document).ready() if there is not a good reason for it. You can define the functions outside and then call them in the $(document).ready().
I have a web page that load a lot of javascript files.
Each javascript do a specific action.
I'm using this model in each javascript file:
"use strict";
$(function() {
var self = this;
// some code
var func1 = function() {
// do some action
};
var runTimer = function() {
func1();
setTimeout(self.runTimer, 60000);
}
});
BUT "this" in this case point to html document and I would like to point to the function itself.
How can I achieve it?
Is there any better "model" to use?
My webpage is like a lot of widgets running at same time and each javascript file run a specific widget.
Thank you very much.
I am not seeing a proper reason for you doing this. If you want to assign a function to a variable just use:
var functionVariable = function() { ... }
Maybe if you tell us why you want to do this out answers will be more specific.
From what you've written it looks like you want to call func1() every 60 seconds. Rather than set up a function like runTimer() that recursively calls setTimeout, just use setInterval. Rather than having the function runTimer(), just use:
var timer = setInterval(func1, 60000);
and if/when you want to cancel this and stop func1 being called, use:
clearInterval(timer);
From what I can see you're only using self/this to achieve this, and there's a better/more straightforward way of doing this. If there's another reason you want to set self=this, can you add to your code sample or try to clarify what you want to acheive?
Have a look at the proxy function: it does exactly that
I am new to javascript and I'm a bit confused about what I'm doing wrong.
so, I have functions defined in an external .js file like so...
var game = (function () {
function start_game() {
...
}
function step() {
...
}
...
}
Now I want my html page to call these functions; first start_game() once, and then step repeatedly every second or so.
I have tried following the code for doing this in HTML in several posts on this subject but in every case my code is never actually executed... What do I do?
Not sure why your wrapping all your named functions in an anonymous function like that. (Prob trying something like an IIF) However since your a beginner, take a step and start with something a little more basic.
<input type="button" onclick="start_game()" value="click to begin" />
<script>
function start_game() {
...
}
</script>
As for having something call a function repeatedly every x seconds. Have a look at something like setTimeout. http://www.w3schools.com/jsref/met_win_settimeout.asp
$(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
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);