I want to make a little 'loading...' widget for my website, using javascript.
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setTimeout("count",50)
document.write(message)
document.write(percent)
document.write(per)
}
But it isn't running. I think I've got some mistake (or maybe totally wrong). How can I do this? I want to update the shown message every 50ms.
try with interval and clear it when progress is finished:
<!DOCTYPE html>
<html>
<head>
<title>testing</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="progress">MSG</div>
<script type="text/javascript">
var percent = 0;
var message = "Loading... ";
var per = "%";
var dom = document.getElementById('progress');
var iv = setInterval(function(){
console.log(message);
dom.innerHTML = ((percent++) + per +' '+ message);
if(percent === 100){
console.log("Loading end.");
clearInterval(iv);
return false;
}
}, 50);
</script>
</body>
</html>
try
setInterval(count,50);
instead of setTimeOut("count",50)
You want to set an interval which runs every x milliseconds, passing in an anonymous function to call the function to call
var percent=0;
var message="Loading... "
var per="%"
function count(){
percent=percent+1;
if(percent==100){
alert("Loading end.")
}else{
setInterval(function() { count() },50)
document.write(message)
document.write(percent)
document.write(per)
}
} <--- you were also missing this ending brace
Script:
var percent = 0;
var message = "Loading... ";
var per = "%";
$(document).ready(function () {
count();
});
function count() {
percent = percent + 1;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(function () {
count();
}, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
see this fiddle for more http://jsfiddle.net/8nhmU/19/
See this jsfiddle
HTML:
<span id="loading"></span>
Javascript:
var percent = 0;
var message = "Loading...";
var per = "%";
var element = document.getElementById('loading');
var interval = setInterval(function() {
element.innerHTML = message + percent + per;
percent += 1;
if(percent > 100) {
clearInterval(interval)
};
}, 50)
The code in your example is missing a great deal of semi-colons and the ending curly-bracket, but that's not the end-issue.
The "problem" with your call to setTimeout is that the first argument must be an actual function, not a string. If you remove the quotes around the call, it will work.
Here is a copy of your code, re-formatted:
var percent=0;
var message="Loading... ";
var per="%";
function count() {
percent++;
if (percent == 100) {
alert("Loading end.");
} else {
setTimeout(count, 50);
document.write(message);
document.write(percent);
document.write(per);
}
}
You are doing it wrong way. You should call the setInterval method when window loads. And when loading is completed, you should stop interval by clearing it using its ID.
var countId;
window.onload = function(){
countId=setInterval(count,50);
}
function count(){
if(per=99){
clearInterval(countId);
}
per++;
//show your message
}
Related
I am trying to make text on my site update. The variable in JS does, but the text on screen doesn't. (Yes I know the code is sloppy, I get it to work and then go through and make it pretty.)
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var moneyText = String(moneyTotal); //Variable for text
var OD2Clicked = 0;
</script>
<script>document.write("<h1 class='money'>Total: $"+ moneyText + "</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked & OD2Clicked==0) {
OD2Clicked = 1;
Adding(20);
console.log("Adding");
}else if(document.getElementById('OD').checked & OD2Clicked>0){
OD2Clicked = 0;
Adding(-20);
console.log("Subtracting");
}
setTimeout(function() {Check()}, 5000);
}
function Adding(m1){ //Function for adding
moneyTotal += m1;
moneyText = String(moneyTotal);
console.log(moneyTotal);
console.log(moneyText+" Text");
}
</script>
Just like I mentioned above in the comment:
Your screen write happens only once when Browser will parse all tags. You need to update your text on the screen every time you modify the value.
Would this work for you?
<script>
var moneyTotal = 370; //Variable for money, filled with starter money
var OD2Clicked = false;
var timeoutPeriod = 5000;
</script>
<script>document.write("<h1 class='money'>Total: $0</h1>"); //Line for updating site </script>
<script>
function Check(){ //Function that checks for radio button change
if (document.getElementById('OD2').checked) {
if (!OD2Clicked) {
OD2Clicked = true;
moneyTotal += 20;
console.log('Adding');
} else if (OD2Clicked) {
OD2Clicked = false;
moneyTotal -= 20;
console.log('Subtracting');
}
// Find DOM element we need to update
document
.querySelectorAll('.money')[0]
.textContent = 'Total: $' + moneyTotal;
}
setTimeout(Check, timeoutPeriod);
}
</script>
I am creating a script which will refresh "viewers" count displayed at the top of my website.
Javascript:
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('viewers.php');
}, 5000);
}
</script>
HTML:
<span id="viewers">0</span>
viewers.php output:
100
I'd like to add a "count up/down" effect, so for example if the viewers.php outputs 200, it will then count up after the 5000 milliseconds, and if this count dropped to 50, the 100 will count down to 50.
Thanks for the help!
Here is a solution that counts up or down to the new number of viewers over a given delay period. It seems to run a little slow, probably due to the delay of my code inside the setInterval.
Just call the setViewers whenever you want to update the count.
<script type="text/javascript">
window.onload = function(){
var delay = 4000;
var viewers = $("#viewers");
var auto_refresh = setInterval(
function ()
{
var curViewers = Number(viewers.html())
$('#viewers').load('viewers.php', function(){
var newViewers = Number(viewers.html());
setViewers(curViewers, newViewers);
});
}, 5000);
function setViewers(currentNum, newNum){
if(currentNum == newNum) return;
var updateSpeed = delay / Math.abs(currentNum - newNum);
var countDir = currentNum > newNum ? -1 : 1;
var timer = setInterval(function(){
currentNum += countDir;
viewers.text(currentNum);
if(currentNum == newNum) clearInterval(timer);
}, updateSpeed);
}
}
</script>
I have an span element. When hovering it, I expected it to change to hello1 -> hello2 -> hello3 every 1 second, but it is not working like that, why?
i = 0;
$('div').on('mouseenter', function() {
interval = setInterval(function() {
$('div').html('<span>hello' + i +'</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span></div>
Your i is incremented outside the setInterval meaning it will only increment on mouseenter. You should also clear the interval each time you mouseenter to avoid lots of intervals going at the same time
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/
Alternatively if you want the code to only increment on hover and to reset when you stop hovering use the following
i = 1;
var interval;
$('div').hover(function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').html('<span>hello' + i + '</span>');
i++;
}, 1000)
},
function() {
clearInterval(interval);
i = 1;
$('div').html('<span>hello</span>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
https://jsfiddle.net/wt73c6bs/1/
I think you want to use .append() instead of .html()
i = 1;
var interval;
$('div').on('mouseenter', function() {
clearInterval(interval);
interval = setInterval(function() {
$('div').append('<span>hello' + i + '</span>');
i++;
}, 1000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>hello</span>
</div>
Here's a simple version with pure JavaScript!
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>Hello 0</span>
<script>
var innerNumber = 0; // The number that will increments.
var span = document.querySelector('span'); // Adding some reference to the element and event handlers.
span.addEventListener('mouseover', setInterval(changeText, 1000));
function changeText(){
span.innerHTML = 'Hello ' + (innerNumber + 1); // Obtaining the content of the element and adding 1.
innerNumber = innerNumber + 1;
}
</script>
</body>
</html>
Display dynamic value in confirm box. This is how i wanted it to work but it didnt. Can anyone tell me how it is done properly.
<script type='text/javascript'>
setTimeout(function(){
var url = document.URL;
var r = confirm("Your session is about to be timedout in " + for (var i = 10; i > 0; i--){ i } + " seconds! Would you like to logged in?");
if (r == true) {
location = url;
} else {
location = '../logoff.php'
}
}, 10000)
</script>
Aside from the flawed string concatenation logic, you cannot achieve this in a standard confirm box. The value is set when the box is instantiated and cannot be changed.
To do what you need you would need to use a modal plugin of some description which you have HTML/JS control over.
This is a work around example:
$(function() {
var out = $('#out'),
sec;
(function() {
var th = setInterval(function() {
sec = parseInt(out.text()) || 0;
if (!sec) {
clearInterval(th);
timeout();
} else {
sec--;
out.text(sec);
}
}, 1000);
})();
var timeout = function() {
if ($('#in').prop('checked')) {
alert('login ...');
} else {
alert('don\'t login ...');
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<center>
<h2>Your session is about to be timedout in <span id="out">10</span> seconds! Would you like to logged in?
<br/>
<input type='checkbox' id='in'/>Yes
</h2>
</center>
<!DOCTYPE html>
<html>
<head>
<script>
function timer(x) {
if (x == 1) {
//reset timer
}
var i = 0;
var timer = setInterval(function() {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 500);
}
</script>
</head>
<body>
<p id="demo">hello</p>
<button type="button" onclick="timer(0)">change</button>
<button type="button" onclick="timer(1)">reset</button>
</body>
</html>
I want to reset timer onclick . e.g. if setIntervaltime is set to 5 sec and 3 seconds are elapsed ,after that if some on click on reset button it should start gain from 5 seconds.How to do this.
Keep the return value of setTimeout somewhere that you can get it again (currently you are storing it in a local variable, so it goes away when the function ends)
Call clearTimeout(timer);
Call setTimeout with whatever arguments you want again.
As already Quentin mentioned, use clearInterval to solve your problem.
Wrap it within an if.else.. statement like
if(x == 1) {
clearTimeout(timeout);
}
else {
timeout = setInterval..... // otherwise even after resetting
// it will continue to increment the value
}
Complete Code:
var timeout; // has to be a global variable
function timer(x) {
var i = 0;
if (x == 1) {
clearTimeout(timeout);
document.getElementById("demo").innerHTML = i;
} else {
timeout = setInterval(function () {
var x = document.getElementById("demo").innerHTML = i;
i = i + 1;
}, 1000);
}
}
JSFiddle