.innerHTML with setTimeout prints only the last part in loop - javascript

I am new to JavaScript.
What I want to do is print the elements of an array one by one on the same location, but after a specific time interval.
Here it prints only the last element.
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<script>
const words = [ "Word1" , "word2" , "word3" , "word4" ];
for (let i = 0; i < words.length; i++ ) {
console.log(words[i]);
setTimeout(function(){ document.getElementById('test').innerHTML = words[i]; }, 2000);
}
</script>
</body>
</html>

You can try this,it prints all one after the other
const words = ["Word1", "word2", "word3", "word4"];
for (let i = 0; i < words.length; i++) {
console.log(words[i]);
setTimeout(function() {
document.getElementById('test').innerHTML += words[i];
document.getElementById('test2').innerHTML = words[i];
}, 2000 * i);
}
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<p id="test2"></p>
</body>
</html>

You are using the wrong function.
A timeout just pauses the script for a period of time, what you are looking for is setInterval.
<!DOCTYPE html>
<html>
<head>
<title>sample</title>
</head>
<body>
<p id="test"></p>
<script>
const words = ['Word1', 'word2', 'word3', 'word4'];
i = 0;
const counter = setInterval(foo, 1000);
function foo() {
document.getElementById('test').innerHTML = words[i];
i++;
if (i >= 4) clearInterval(counter);
}
</script>
</body>
</html>

Related

Problems with javascript html dom

let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i]
document.body.append(p)
console.log(tasks)
}
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>
Basically i have this problem when i hit my add button second time it add again the first element from the array butt how do i manage to show only the last element without the first one in the next p elements when i hit add button
If you need list of p
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
const instance = document.getElementById("t")
instance.innerHTML = '';
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i];
instance.appendChild(p);
}
}
If I understand your need correctly, you do not want to "repeat" displaying "task" entered previously (which will result in displaying previous input tasks multiple times) when you perform entering new task(s).
In that case, please clear the element "t" before you update it.
So the HTML is
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="enter the task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<div id="t"></div>
</body>
</html>
and the JS (motor.js) is
let tasks = []
function addV(){
if (document.getElementById("bara").value !=""){
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
var tempstring=""
for(let i = 0;i<tasks.length;i++){
tempstring=tempstring +"<br>"+ tasks[i];
//const p = document.createElement("p");
// p.innerText += tasks[i]
// document.body.append(p)
}
document.getElementById("t").innerHTML=tempstring;
document.getElementById("bara").value="";
}
}
Your DOM p tag was inside the loop thus out of scope. I also created a new taskArray to hold the new tasks. This can be seen in the console log and the innerHTML is now displaying each new task just the one time.
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
let taskArray = [];
const p = document.createElement("p");
for (let i = 0; i < tasks.length; i++) {
p.innerText = tasks[i]
document.body.append(p)
taskArray.push(tasks[i]);
}
console.log(taskArray);
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>

function to return something x amount of times,specified by a parameter? [duplicate]

This question already has answers here:
Repeat a string in JavaScript a number of times
(24 answers)
Closed 1 year ago.
I have a function which returns an html element like addSpan(times),is there a way to return this element as many times as specified in the parameter items ?
vanilla js is welcomed!
function addSpan(times){
const span = `<span>This is a span</span>`
return span
}
$("body").append( addSpan(2) ) //is supposed to add 2 spans
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Please use Array.map() function.
function addSpan(times){
const spans = [...Array(times)].map(val => "<span>This is a span</span>").join('')
return spans
}
use yield
function* addSpan(times){
for(var i=0; i < times; i++){
const span = document.createElement('span');
span.innerText = "Some text" ;
yield span;
}
}
for (let element of addSpan(2)) {
$("body").append(element)
}
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>
Yes. Possible.
Like this:
function addSpan(count)
{
let result = "";
for (var i = 0; i < count; i++)
{
result += "<span>This is a span</span>";
}
return result;
}
You need loop until you reach the count and return spans.
function addSpan(times){
let spans = "";
const span = `<span>This is a span</span>`;
for (let i = 0; i < times; i++){
spans += span;
}
return spans;
}
$("body").append(addSpan(2));
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
</body>
</html>

how to initialize a member of JS array?

I just wrote this in order to take n from user and also n names , and then print them on screen after clicking on button , but i cant initialize my array ...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script>
var n;
var i =0;
var names = [];
function mf1(){
n=parseInt(document.getElementById("n").value);
}
function mf2(){
if (i<n){
names[i]=document.getElementById("nam").value;
i++;
document.getElementById("rem").innerHTML=names[i];
}
}
</script>
inset n : <input type="text" id="n"> <button onClick="mf1()">take n</button>
insert name: <input type="text" id="nam"> <button onClick="mf2()"> take name</button>
<p id="rem"></p>
</body>
</html>
The problem is that in function mf2 you can't access names[i] because you increment i++ before.
var n;
var i = 0;
var names = [];
var input1 = document.getElementById("n");
var input2 = document.getElementById("nam");
function mf1(){
n = parseInt(input1.value);
console.log(n);
}
function mf2(){
if (i < n){
names[i] = input2.value;
console.log(names);
document.getElementById("rem").textContent = names[i];
i++;
}
}

What's wrong with this javascript code? (body script calling head function)

Why does the following not produce any result? I get a blank page. I kept modifying/simplifying the code to see where the problem is and it seems to be with the line
"var count = NbnamePattern(names)"
Things seem to work when the body script calls a function defined in the head but with no arguments passed.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(var names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>
function NbnamePattern(var names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
should be
function NbnamePattern(names){
var count = 0;
for(var i in names)
if(names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
return count;
}
The functions in javascript dont take types, it should just be name
you need to remove the var from NbnamePattern(var names) function
<!DOCTYPE html>
<html lang="en">
<head>
<title>Assignment 2 Q4</title>
<meta charset="utf-8" />
<script>
function NbnamePattern(names) {
var count = 0;
for (var i in names) {
if (names[i].search(/ie$/) != -1 || names[i].search(/y$/) != -1)
count++;
}
return count;
}
</script>
</head>
<body>
<p></p>
<script type="text/javaScript">
var names = new Array("freddie", "bob", "mieke", "yahoo2", "georgey"); var count = NbnamePattern(names); document.getElementsByTagName("p")[0].innerHTML = "The number of names having these two patterns (/ie$/) and (/y$) in the array is:" + count;
</script>
</body>
</html>

Finding Factorial of a number through prompt from the user

I have been struggling with the this output from which hangs my browser. When I run the following code it runs fine.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = 5;
for(var i=1;i< 5;i++){
input = i*input;
}
document.write(input);
</script>
</body>
</html>
But this hangs the browser and I have to stop it finally. I cant't find any bug or error in this code.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = prompt("Enter the number to get factorial of: ");
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
</script>
</body>
</html>
input = i*input; increases input so i < input is always false. Try smth like
var input = parseInt(prompt("Enter the number to get factorial of: "));
var result = input;
for(var i=1;i < input;i++){
result = i * result;
}
document.write(result);
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function fact(num)
{
var x=parseInt(num);
if(x>0)
x=x* fact(x-1);
alert(x);
}</script>
</head>
<body>
<form name="f1">
Enter the Number :<input type="text" length="8" name="txt1"><br>
<input type="button" value="Find factiorial" onclick="fact(txt1.value)">
</form>
</body>
var y = prompt("type number ");
var x = input;
function fact(x) {
if(x==0) {
return 1;
}
return x * fact(x-1);
}
function run(number) {
alert(fact(parseInt(number, 10)));
}
run(x);

Categories