Inappropriate use of setInterval - javascript

<html>
<head>
<script type="text/javascript" language="JavaScript">
var inter;
var seconds = 1;
function recharge()
{
inter = window.setInterval( "printA()" , 1000 );
}
function printA()
{
document.write( "you are here: " + seconds + " seconds" );
seconds++;
}
</script>
</head>
<body>
<button onclick="recharge();"> Start </button>
</body>
</html>
my problem is... recharge() contains a setInterval() that contains a function printA() this
function that does is print whit a document.write a variable that sum one every time that recharge
is called.. but just print 1 and doesnt print the next number. I tried whit a alert instead of document.write
and its work so I don't know what i am doing wrong. i am a noob. Thanks for your help.

So as I'm understanding your question and comments, you want to print something like this:
you are here: 2 seconds
you are here: 3 seconds
you are here: 4 seconds
I would recommend doing something like this:
<html>
<head>
<script type="text/javascript" language="JavaScript">
var inter;
var seconds = 1;
function recharge()
{
inter = window.setInterval( "printA()" , 1000 );
}
function printA()
{
document.body.innerHTML += "<div>you are here "+seconds+" seconds</div>";
seconds++;
}
</script>
</head>
<body>
<button onclick="recharge();"> Start </button>
</body>
</html>
The += will keep appending html to the document.

When you document.write(), the whole page is re-written, meaning all your JavaScript is lost. alert() should work however - what did you try? The innerHTML method by winhowes works probably best. Also I don't see what 'recharge();' is supposed to achieve.

Related

Undefined when doing document.write() with button OnClick="counter"

I'm new to programming and would need some help, why the document.write() didn't work and basically the page crashes... Can anyone help me?
<!DOCTYPE html>
<html>
<head>
</head>
<script type="text/javascript">
function showText() {
var x;
var counter;
if ( x === 0) {
counter = 0;
x = 1;
}
counter = counter + 1;
document.write("Times clicked: " + counter);
}
</script>
<body>
<script type="text/javascript">
showText();
</script>
<button onclick="showText();">Click Me!<button>
</body>
</html>
Avoid using document.write
Quoting from the MDN Developer Network documentation page:
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
So basically, your issue is using document.write after the page has loaded: this will result in deleting the entire content of the page and displaying that string.
Also, your code doesn't work because your count variable is declared inside the showText function, and you're trying to access it outside of it, running into an error.
Solution
To make your code work you should create another element, let's say a <p> element, and display the text inside of it. Here's an example of a correct page:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me!</button>
<p id="txt">Times clicked: 0</p>
<script type="text/javascript">
function showText() {
count++;
text.textContent = "Times clicked: " + count;
}
var count = 0,
button = document.getElementById("btn"),
text = document.getElementById("txt");
button.addEventListener("click", showText);
</script>
</body>
</html>
Check out a live demo here.

NaN error - Dealing with strings and integers

Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.
It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>

Refreshing a div every 30 seconds [duplicate]

I'm working with a nice little Jquery that auto loads and refreshes a div every bla bla Seconds.
Works perfectly on all browsers then I load up IE and bang what a surprise no luck! :(
Index.html
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').load('reload.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
<body>
<div id="load"> </div>
</body>
</script>
reload.php
<?
echo time(); //just a timestamp example..
?>
Any ideas guys?
Add a random value at the end of the url to avoid caching.. That should solve your problem. ex: $('#load').load('reload.php?_=' +Math.random()).fadeIn("slow");
Try closing your script tag before having your body tag.
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').load('reload.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body>
<div id="load"> </div>
</body>
body {text-align:center; background-image: url('http://cdn3.crunchify.com/wp- content/uploads/2013/03/Crunchify.bg_.300.png')}
$(document).ready(function() {
auto_refresh();
});
function auto_refresh(){
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text('I am getting refreshed every 3 seconds..! Random Number ==> '+ randomnumber);
}
var refreshId = setInterval(auto_refresh, 1000);

How can I do the same thing but in HTML not JavaScript dialog?

My code enables popping up alert dialog at the same time as the elapsed time goes by.
How can I do the same thing but in HTML not JavaScript dialog?
Do I have to do it with something related to AJAX?
Can anyone show me an example, please?
jQuery(document).ready(function () {
var comments = [{'time':'5','message':'hello! 5 secs has past'},{'time':'10','message':'hello! 10 secs has past'},{'time':'30','message':'hello! 30 secs has past'}];
$('#video').on('timeupdate',function(e){
showComments(this.currentTime);
});
function showComments(time){
var comments = findComments(time);
$.each(comments,function(i,comment){
alert(comment.message);
});
}
function findComments(time){
return $.grep(comments, function(item){
return item.time == time.toFixed();
});
}
});
HTML
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Show sequential messages in HTML</h1>
<p>
**Messages appears here instead of dialog**
</p>
</body>
In your showComments function, replace this line:
alert(comment.message);
Into these:
var messages = $('p').text();
$('p').text(messages + comment.message + "\n");
// Show for 5 seconds, then hide the `p` element.
$('p').show().delay(5000).fadeOut();
That way, it will fill the paragraph with the comment message(s).

Issues with JavaScript settimeout function

I am very new to JavaScript and cannot seem to get the setTimeout command to do anything. I know this has been asked many times before, but I have spent the last two hours looking at all previous cases of it and it still isn't working for me. Here is what I have got at the moment:
<html>
<script type="text/javascript">
var i = 0;
function aloop() {
document.write(i);
i++;
}
function afunction() {
if (i <= 12) {
setTimeout(aloop(), 1000);
afunction();
}
}
</script>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</html>
Can anyone tell me what I should do to make this work?
Pass a function to setTimeout, not the return value of a function call.
setTimeout(aloop,1000);
The problem is you're calling your function instead of queuing your function.
setTimeout(aloop, 1000) NOT setTimeout(aloop(), 1000);
You didn't describe what doesn't work, but I'll assume you want the i to be written in 1000 millisecond intervals.
Do this:
<html>
<!-- you're missing your head tags -->
<head>
<title> my page </title>
<script type="text/javascript">
var i=0;
function aloop() {
// don't use document.write after the DOM is loaded
document.body.innerHTML = i;
i++;
afunction(); // do the next call here
}
function afunction() {
if (i<=12) {
// v---pass the function, don't call
setTimeout(aloop,1000);
// afunction(); // remove this because it'll call it immediately
}
}
</script>
</head>
<!-- you're missing your body tags -->
<body>
<form>
<input type=submit value="Click me!" onClick="afunction()">
</form> <!-- you're missing your closing form tag -->
</body>
</html>

Categories

Resources