I want the letters 'q' to be written only once per second.
But it doubles every second.
How to do this with this command?
function writeNow() {
document.write('q');
setInterval(writeNow, 1000);
}
writeNow();
You can use setTimeout
function writeNow() {
document.write('q');
setTimeout(writeNow, 1000);
}
writeNow();
Or setInterval
function writeNow() {
document.write('q');
}
setInterval(() => {
writeNow()
}, 1000);
You want to set the interval outside the function, when you call it inside the function, it will be recursive
Try
function writeNow() {
document.write('q');
}
setInterval(writeNow, 1000);
writeNow();
And I highly recommend against document.write as it is deprecated
But it doubles every second
Because you are calling the setInterval inside the method. So it looks like recursion
Solution:
You should move setInterval(writeNow, 1000); outside the called function - writeNow.
Syntax
setInterval(function, milliseconds, [param1, param2, ...])
function writeNow() {
document.write('q');
}
setInterval(writeNow, 1000);
Try this
<script>
function writeNow() {
document.write('this');
}
setInterval(writeNow, 1000);
</script>
You were calling a function recursively
The below code does the job. May be able to fine tune a bit to improve performance:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<style media="screen">
#letters
{
padding: 10px;
margin: 10px;
}
</style>
</head>
<body>
<div id="letters">
</div>
</body>
<script type="text/javascript">
let alphabets = [];
let running = false;
let output = "";
function prepare()
{
for(i=65; i<92; i++)
{
console.log(String.fromCharCode(i));
alphabets.push(String.fromCharCode(i));
}
}
let lastPrinted = 0;
function printAlphabet()
{
if(lastPrinted == 0)
{
running = true;
}
else if(lastPrinted == 26)
{
running = false;
}
if(running)
{
output += (alphabets[lastPrinted]) + ","
document.getElementById('letters').innerHTML = output;
lastPrinted ++;
setTimeout(printAlphabet, 1000);
}
else
{
output = output.substring(0,output.length - 1)+".";
document.getElementById('letters').innerHTML = output;
}
}
prepare();
printAlphabet();
</script>
</html>
Output:
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
Related
The following code is intended to display a 0, then a few seconds later change this to 1, then back to 0, and so on, ad infinitum.
The problem is this (obviously) freezes the webpage itself. I could use an animated gif but want to expand this further and code becomes the better choice.
How might I do this?
<div id="bit" style="width: 100px; height: 100px; margin: auto; border: 1px solid #000; text-align: center;"></div>
<script>
var bitValue = 0;
for (;;) {
setTimeout(showBit(), 2000);
}
function showBit() {
document.getElementById("bit").innerHTML = bitValue;
bitValue = Math.abs(bitValue - 1);
}
</script>
A few things went wrong:
setTimeout(showBit(), 1000);
must be:
setTimeout(showBit, 100);
as you want to pass a function and not execute it immeadiately. Another thing is that you cannot just do
for(;;) { /*...*/ }
as that blocks the browser forever. You would have to do it asynchronously:
const delay = ms => new Promise(res => setTimeout(res, ms));
(async function() {
while(true) {
await delay(1000);
showBit();
}
})();
Or a bit simpler with a pseudorecursive timeout:
(function next() {
showBit();
setTimeout(next, 1000);
})();
Or if you dont want to do that manually, just use setInterval:
setInterval(showBit, 1000);
Like #CertainPerformance said, setInterval should be used instead. Here are a few good examples of how it can be used - https://www.w3schools.com/jsref/met_win_setinterval.asp
Use **setInterval()** with **Math.round** and **Math.random**?
var time = setInterval(f, 2000);
function f() {
document.getElementById("bit").innerHTML = Math.round(Math.random());
}
Use if
var time = setInterval(function() {
if (document.getElementById("bit").innerHTML == 0) {
document.getElementById("bit").innerHTML = 1;
}
else {
document.getElementById("bit").innerHTML = 0;
}
}, 2000);
Is there an easy way to output content when inside a Javascript loop, rather than have it display on screen after the loop has completed.
Code e.g:
var c = 0;
while (c <=1000 ){ //100000
run();
c++;
}
function run() {
console.log(c);
$('#data').append(c);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<div id="data"></div>
It outputs to console straight away (during loop) but on screen does not.
Hoping someone can assist.
Thanks!
Are you wanting to write it to the webpage?
If so then you can write it to a div using the InnerHTML
document.getElementById("yourDivID").innerHTML = yourString;
Your browser's Javascript engine is too fast thus you cannot see the changes in real time. So set a timer and slow down the process.
Run the below code and see the magic happens...
var c = 0;
$(document).ready(function () {
run();
});
function run() {
var timer = setInterval(function () {
//console.log(c);
$('#data').append(c + "\n");
if (c++ == 1000) {
clearInterval(timer);
}
}, 12); //set time in milliseconds
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>
These are the changes made to your code :
Removed the while loop and replaced it with setInterval()
Added $(document).ready() function to make sure the run() is executed after the DOM is fully loaded.
Try using clousres and setTimeout:
function run(c) {
console.log(c);
$('#data').append(c + ', ');
}
$(function() {
for (var c = 1; 999 > c; c++) {
(function(c) {
setTimeout(function() {
run(c);
}, 1);
})(c);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data"></div>
I am wondering why this code is working in a project for itself but as soon as i add a window.addEventListner("load") function it stops working.
Original working code
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<button id="click">Click</button>
</body>
</html>
<script>
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
</script>
Modified Javascript code which gives me this error 'ReferenceError: test is not defined.
window.addEventListener('load', function () {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
}
finally,i know what you mean ,try to run this on your console:
var site = "global";
function foo() {
var site = "partial";
setTimeout('alert(site);', 100);
}
foo();
ok,tell me ,what do you got ? partial or global?
sorry,it is 'global'!
that is because,string in the setTimeout(the first argument ) is executed in the global scope,so when the 'alert(site)' executing , it will find
var site = "global";
and will never find
var site = "partial";
because this site is in the function foo scope,in general,we can't visit variable defined in the function scope out of the function except closure.
in this case,we can not visit variable site defined in the foo in the global scope.
so,if you don't define site in the global ,you will get the error ,for example:
var s = "global";
function foo() {
var site = "partial";
setTimeout('alert(site);', 100);
}
foo();
what do you got ?
Uncaught ReferenceError: site is not defined
that is exactly why you got error after you add a window.addEventListner("load") function.Now,pay attention to the following codes ,especially comments.
<script>
// when you visit function test in the setTimeout,you visit it here!
// you didn't define another function test in the global,
//if you defined,it will execute this function test
window.addEventListener('load', function () {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
// you can't visit function test in the global,because function test is defined in this anonymous function
}
document.getElementById("click").addEventListener("click", function (e) {
test();
}, false);
});
</script>
keep going ,see this
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<button id="click">Click</button>
</body>
</html>
<script>
function test() {
console.log('in the global')
};
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout("test()", 1000);
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
});
</script>
what do you got ?
0
in the global
so,i guess you understand now,we are going to talk about how to fix the problem,just remove the "" or '' and (),use the function name is fine.
timeout = setTimeout(test, 1000);
this will make it execute normally.actually,we do not use the following type,
timeout = setTimeout("test()", 1000);
due to historical reasons,you can stil see this kind of code ,but we don't suggest,and it will consume performance,that's all,hope you understand.
There is a syntax error, closing ) is missing
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout(test, 1000); //observe this change as well.
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
}); //this final `)` was missing
Demo
window.addEventListener('load', function() {
var count = 0;
var timeout;
function test() {
console.log(count);
count = count + 1;
timeout = setTimeout(test, 1000);
}
document.getElementById("click").addEventListener("click", function(e) {
test();
}, false);
});
<button id="click">Click</button>
Note
Following line in your code
timeout = setTimeout("test()", 1000);
causes
"message": "Script error."
Hence has been changed to
timeout = setTimeout(test, 1000);
I have two JavaScript "onload" functions that I am trying to run on a webpage: a visual timer and a auto refresh function. I have implemented both in my webpage but although the timer runs, the Auto Refresh function will not run unless I remove the visual timer function from the script.
Here is the code for the webpage:
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body onload="JavaScript:timedRefresh(15000); timedText();">
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
Any help in solving this problem would be greatly appreciated.
try with a small change:call timedRefresh() inside window.onload's timetext() function not in body onload.
<!DOCTYPE html>
<HTML>
<HEAD>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
<TITLE>test</TITLE>
</head>
<body>
<script>
window.onload = timedText;
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
timedRefresh(15000);
var timer = setInterval(function () {
if(counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
</script>
<input type="text" id="txt" />
</body></HTML>
The problem is the second one overrides the first. That is what you should be using addEventListener to add events.
window.addEventListener('load', timedText, false);
window.addEventListener('load', function(){timedRefresh(15000);}, false);
and if you need to support older IEs you need to look at attachEvent
BUT looking at the code why are you running two setTimeouts when all you need to do is when it hits zero call the redirect.
You can add multiple onload events using the addEventListener method, like so:
window.addEventListener("load", timedText, false);
window.addEventListener("load", timedRefresh(15000), false);
function timedText() {
var txt = document.getElementById('txt'),
counter = 15;
var timer = setInterval(function() {
if (counter === 0) return clearInterval(timer);
txt.value = counter + " seconds";
counter--;
}, 1000);
}
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",
timeoutPeriod);
}
You can find out more information about addEventListener here.
Here's a working codepen.
I'm using Keith Wood's jQuery Countdown timer. http://keith-wood.name/countdown.html
What I want to achieve is a countup with stop and resume buttons, and controls to add and subtract minutes and seconds:
I create a countup (from 0 to 60 minutes) and pause it right away, like this:
$('#contador_tiempo').countdown({
since: 0,
format: 'MS',
layout: '{mnn}{sep}{snn}'
});
$('#contador_tiempo').countdown('pause');
But it seems that it's still running in the background. When I click the buttons to add or subtract, the functions do the operations on top of that background counter, not the displayed counter.
Full code on JSFiddle, with the behaviour reproduced:
http://jsfiddle.net/J2XHm/4/
(Play a bit with the controls and you will see that it keeps counting although it's paused.)
Yes, there is a bug in the 'getTimes' command - it recalculates when paused. I'll make the correction in the next release (1.6.2) but in the meantime you can change the _getTimesPlugin function:
_getTimesPlugin: function(target) {
var inst = $.data(target, this.propertyName);
return (!inst ? null : (inst._hold == 'pause' ? inst._savePeriods : (!inst._hold ? inst._periods :
this._calculatePeriods(inst, inst._show, inst.options.significant, new Date()))));
},
If you can accept lightweight code, i.e. without using the jQuery countdown timer, the following might help you:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://localhost/web/JavaScript/jQuery/jquery"></script>
<script type="text/javascript">
var countUpSeconds = 0;
var interval = null;
function displayTime() {
$("#timeContainer").text(format(Math.floor(countUpSeconds/60))+":"+format(countUpSeconds%60));
}
function playStop() {
if(interval) {interval=window.clearInterval(interval);}
else {interval = window.setInterval(countUp, 1000);}
}
function countUp() {
++countUpSeconds;
if(countUpSeconds >= 3600) {/* do something when countup is reached*/}
displayTime();
}
function format(s) {return s<10 ? "0"+s : s;}
$(function() {
displayTime();
$("#playStop").on("click", function () { playStop(); } );
$("#addMin").on("click", function () { countUpSeconds += 60; displayTime(); } );
$("#subMin").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-60); displayTime(); } );
$("#addSec").on("click", function () { countUpSeconds += 1; displayTime(); } );
$("#subSec").on("click", function () { countUpSeconds = Math.max(0, countUpSeconds-1); displayTime(); } );
});
</script>
</head>
<body>
<div id="timeContainer"></div>
<button id="playStop">Play/Stop</button>
<button id="addMin">+1 minute</button>
<button id="subMin">-1 minute</button>
<button id="addSec">+1 second</button>
<button id="subSec">-1 second</button>
</body>
</html>