This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
Closed 2 years ago.
I am trying to make a script where while var < 1, it pastes letters, but it makes my screen crash. I tried seeing some questions here on StackOverflow, but the code doesn't line up with mine. I want the interval to be every 2 milliseconds
My code:
<template>
a
</template>
<html>
<head>a</head>
<body onLoad="pasteContent()">
</body>
<script>
while (true) {
function pasteContent() {
var i = 0;
var temp = document.getElementsByTagName("template")[0];
var clon = temp.content.cloneNode(true);
document.body.appendChild(clon);
}
}
</script>
</html>
Use setTimeout? Just set the timeout to 2 since it uses milliseconds.
Here's an article on it: https://www.w3schools.com/jsref/met_win_settimeout.asp
Use setInterval():
let div = document.querySelector('.div')
let intervalId = setInterval(writeLetter, 1000)
function writeLetter(){
if(div.innerHTML === 'aaaa'){
clearInterval(intervalId)
}else{
div.innerHTML += 'a'
}
}
<div class='div'></div>
Related
This question already has answers here:
How to add bold text using javascript
(3 answers)
Closed 1 year ago.
So i have this array of question written in js. And i access to my html using this:
const questionIndex = availableQuestion[arrayReady[currentPage-1]];
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;
how can i make a certain word like = "not","except" from currentQuestion.q bold?
You need a list of words to be bolded, iterate over them, find them in currentQuestion.q, and then bold them.
const currentQuestion = {}
currentQuestion.q = "This is not a not really except good question."
console.log(currentQuestion.q)
const boldWords = ["not", "except"]
boldWords.forEach(word => {
currentQuestion.q = currentQuestion.q.replace(new RegExp("(" + word + ")", "g"), makeBold("$1"))
})
console.log(currentQuestion.q)
function makeBold(str) {
// your bold implementation
return str.bold()
}
I viewed all the answers, but I have developed a more browser compatible code compared to the already existing answers. Please have a look below.
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a string in bold.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
const str = "Hello Javesh, How are you doing today?"; //your question
const result = str.split(" ");
const keywords = ["Hello", "How"]; // your keywords
for(var i = 0; i<result.length; i++){
if(keywords.includes(result[i])){
document.querySelector("#demo").innerHTML += "<b>"+result[i]+"</b>"+" ";
}else{
document.querySelector("#demo").innerHTML +=result[i]+" ";
}
}
}
</script>
</body>
</html>
The bold() function is depreciated as its functionality can vary per browser.
Here's the MDN reference for the bold() function:-
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/bold
You could use the bold() function and combine it with a loop and conditions
You could use bold() <- (that's a function) and use it with loops/conditions
if (document.case.display.value.length >16 && document.case.display.value.length < 21) {
Notiflix.Notify.Info('Because you have a lot of charatchers font size is smaller');
document.getElementById("display").style.fontWeight = "550";
document.getElementById("display").style.fontSize = "2em";
} else if (document.case.display.value.length > 20) {
var str = document.case.display.value.length
Notiflix.Notify.Warning('Max characters you can see is 25 ');
Notiflix.Notify.Failure('Number of your characters' + str);
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "1.5em";
}
else {
document.getElementById("display").style.fontWeight = "500";
document.getElementById("display").style.fontSize = "2.5em";
}}
window.setInterval(function(){
testLength();
}, 100);
Notiflix is a JavaScript library for notification.
I have a display who font go down if have so much characters and i set time every 0.1 second he check number of characters. If number is higher than 16 he put a notification.
But he put every 0.1 second notification i want only one time/s. Do you have idea who can "block " this line of code for 10 second and after that read this without moving settimer down.
Sorry about bad English.
Any information will help me
You can try storing your setInterval() in a variable and calling it only when required. Else, you can stop that using that variable name.
let myInterval;
function start(){
myInterval = window.setInterval(function(){
testLength();
}, 100);
}
function stop(){
clearInterval(myInterval);
}
P.S: I would also like to advice on using onChange eventListener for checking test length rather than setInterval.
Update: Alternate method
You can also try removing setInterval thing and adding something like this:
document.addEventListener("DOMContentLoaded", function(event) {
var numbers = document.querySelectorAll(".digit")
console.log("numbers", numbers);
numbers.forEach(el => el.addEventListener('click', testLength))
});
This question already has answers here:
string.charAt(x) or string[x]?
(7 answers)
Capitalize words in string [duplicate]
(21 answers)
Closed 4 years ago.
TO BE CLEAR:
I don't want to know how to capitalize, but rather I want to know why i can change it in one-dimensional, but not 2-dimensional
I'm doing some coding challenges to get familiar with JavaScript.
I capitalized the first Letter of each word in a given string.
I split the string into a word-seperated array via String.match(regex);
var word_array = str.match(/\w(\w)*/g);
And I then made from the word another letter-seperated array to change single letters. (also with regex)
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
And this works just fine.
But I wanted it a bit shorter, so I tried to do the action on the letter on the second dimension of the word_array, but with no effect at all.
word_array[i][0] = word_array[i][0].toUpperCase();
Full-Code-Snippet
const input = document.querySelector("#string"),
button = document.querySelector("#DOIT");
button.addEventListener("click", function(){
LetterCapitalize(input.value);
});
function LetterCapitalize(str) {
var word_array = str.match(/\w(\w)*/g);
for(let i = 0; i < word_array.length; i++){
//This part works
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
word_array[i] = letter_array.join("");
//this doesn't
/*
word_array[i][0] = word_array[i][0].toUpperCase();
console.log(word_array[i][0]);
*/
}
console.log(word_array);
str = word_array.join(" ");
return str;
}
<input id="string" type="text"/>
<button id="DOIT">DO IT</button>
This wouldnt work wouldn't work since Strings are immutable in javascript. the
letter_array = word_array[i].match(/\w/g);
letter_array[0] = letter_array[0].toUpperCase();
code snipped worked as you converted your strings to a list/array which is mutable by nature. although, id like to point out that this question might be a duplicate. here is a capitalization in javascript question
This question already has answers here:
setTimeout calls function immediately instead of after delay
(2 answers)
Closed 6 years ago.
The following pieces of code uses the function setInterval() to continually update a 'clock'. The only difference is in the function call setInterval().
When I change the setInterval argument from
setInterval('updateTime()',1000);
to
setInterval(updateTime(),1000);
[from single to no quotes], it does not work. Can anyone explain this to me?
Single Quotes:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval('updateTime()', 1000); //////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
No Quotes:
<head>
<script>
function updateTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var now= h+':'+m+':'+s;
document.getElementById('timer').innerHTML = h+':'+m+':'+s;//set the text in 'timer' id below to the date
setInterval(updateTime(), 1000);//////SEE THIS LINE//////
}
</script>
</head>
<body>
<p id='timer'> Time </p>
<script>
updateTime();
</script>
</body>
Online js console for testing can be found here: https://jsfiddle.net/
setInterval('updateTime()', 1000);
You are passing string to the setInterval as the first argument.You need to pass the function reference
Correct Way
setInterval(updateTime, 1000)
Try doing this
setInterval(updateTime, 1000);
without ()
Now coming to the question why.
The Setinterval function evaluates the content if string and executes if function name
To explain why it does execute the updateTime() with brackets immediately is because it tries to execute the output of the updateTime function in interval loop, that will be undefined if you are not returning anything and will be treated as function name if it returns a string. Anything else will be overlooked or error thrown.
Hope that helps
If you change your second code to
setInterval(updateTime,1000);
it should work. The reason is because ^there you're passing a function pointer to set interval while in your answer updateTime() is passing the return value of updateTime to setInterval.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We have a website, on the front page we show "Parcels Shipped", we'd love the numbers to updated via a formula - i.e. we shipped 34,502,233 parcels in 2014... We show a static stat.... But we'd love to have the numbers increased via a formula that increases the number by the second/minute
Thanks for all the replies guys - So we current have this: gyazo.com/d421a3675884e2610d368c9e60e8acca
we want it to increase around 76 times per minute.... so a rotating number basically - i've no idea how to achieve this. (left number) & We want it to increase around 43 times per minute for middle number
Does anyone know where I can find this sort of trick?
This achieves your desired functionality using setInterval() to fire a function that checks to see how long it's been since today. Then, multiplying by the increase you mentioned in the comments and adding it to the numbers in your screenshot.
JS:
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function timeSince() {
var prevTime = new Date(2015,8,8,0,0);
var thisTime = new Date();
return (thisTime.getTime() - prevTime.getTime()) / 1000;
}
function parcelCount() {
var secDiff = timeSince();
var leftNum = document.getElementById("left");
var midNum = document.getElementById("mid");
var leftNumCount = Math.round(((76/60) * secDiff) + 40093794);
var midNumCount = Math.round(((43/60) * secDiff) + 22874098);
leftNum.innerHTML = numberWithCommas(leftNumCount);
midNum.innerHTML = numberWithCommas(midNumCount);
}
parcelCount();
setInterval(parcelCount, 1000);
HTML:
<h3>Left</h3>
<span id="left"></span>
<h3>Mid</h3>
<span id="mid"></span>
Demo: http://jsfiddle.net/hopkins_matt/513ng07d/
Used info from these answers to build this:
https://stackoverflow.com/a/2901298/4556503
https://stackoverflow.com/a/6636639/4556503
Use setInterval with the increasing function as 1st argument and ms as the 2nd one.
var el = document.getElementById('counter')
var x = 0
window.setInterval(function(){
el.value = formula(++x)
}, 1000)
If the increase is completly random, just a "front-end design stuff" (sorry, guys), you can use setInverval() from Javascript.
It works this way:
every _s ms, the function will be called. If you have an increase factor, like a global constant you could do something like:
var myDiv = document.getElementById("myId");
var _mseconds = 1500; // mileseconds
var incFactor = 150;
var handlerInt = setInverval(function() {
myDiv.innerHTML = incFactor+incFactor; // you can use Math.Random() or something, instead
}, _mseconds);
Hope it helps!