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))
});
Related
I am new to javascript, having trouble with this assignment. My professor suggested the problem was due to needing to parseInt, but even after I added the parseInt, it still isn't working.
This displays fine in Firefox, and the "higher" and "lower" statements are displayed, but when I run it in Chrome or Edge, only the window asking for a number will render. I did look for help, but I cant see what I'm doing wrong. Most of the suggestions Ive seen online, don't address the code directly. Is this problem specific code related or something else?
function play() {
let guess;
let randNum = Math.floor(1 + Math.random() * 999);
let guessed = false;
while (guessed == false) {
guess = window.prompt("Enter a number from 1 to 1000");
parseInt(guess);
if (guess == randNum) {
document.writeln("<li>" + "Congratulations! You guessed the correct number!</li>");
guessed = true;
document.writeln("</ol>");
document.writeln("Your guess: " + guess);
document.writeln("Actual number: " + randNum);
} else if (guess > randNum) {
document.writeln("<li>" + guess + " is Too High. Try Again.</li>");
document.writeln("</ol>");
} else if (guess < randNum) {
document.writeln("<li>" + guess + " is Too Low. Try Again.</li>");
document.writeln("</ol>");
}
}
}
window.addEventListener("load", play, false);
Don't use writeln. Use the proper methods like .append() or .insertAdjacentElement() or .insertAdjacentHTML() if you just want to insert HTML strings instead of Nodes.
Don't use alert, prompt, etc. Those Window methods will most likely get deprecated or at least discouraged in the near future.
Remember, use let for variables, and const for constants.
Use DOM methods like Element.querySelector() to get and store a DOM Element,
Use Document.createElement() to create a new one (a new LI Element in your case)
To ease the querying or creation of the desired DOM Elements — create two reusable functions:
// DOM utility functions:
const find = (selector, parent) => (parent || document).querySelector(selector);
const create = (tag, properties) => Object.assign(document.createElement(tag), properties);
that can be used to cache your Elements and use them later in your game logic
// Cache your DOM elements!
const elNumber = find("#number");
const elCheck = find("#check");
const elAnswers = find("#answers");
which will target and cache your three HTML elements by theri id attribute selector. As said above, instead of using prompt, use a better and less invasive UI (User interface) right into your App:
Enter a number from 1 to 10: <input id="number" type="text">
<button id="check" type="button">CHECK</button>
<ol id="answers"></ol>
Then create two let variables for the guessed state and one for the random number, so that when you start a new game you can change their values:
// Make available for multiple games!
let numRand;
let isGuessed;
then, giving your specific game, you need two more functions, one to start (and restart) the game and one for your game logic:
// Call this function to start a new game!
const start = () => {
// Clear old answers
// Reset old guessed state
// Generate a new random number
};
// Call this function on button CHECK click!
const check = () => {
// Game logic goes here!
}
// Assign listener to button:
elCheck.addEventListener("click", check);
// Start a new game!
start();
Demo time:
// DOM utility functions:
const find = (selector, parent) => (parent || document).querySelector(selector);
const create = (tag, properties) => Object.assign(document.createElement(tag), properties);
// Task:
// Cache your DOM elements!
const elNumber = find("#number"); // PS: remember, use const for constants!
const elCheck = find("#check");
const elAnswers = find("#answers");
// Make available for multiple games!
let numRand;
let isGuessed; // Try to prefix boolean variables with "is*"
// Call this function to start a new game!
const start = () => {
// Clear old answers:
elAnswers.innerHTML = "";
// Reset old guessed state
isGuessed = false;
// Generate a new random number 1 to 10:
numRand = Math.floor(Math.random() * 9) + 1;
};
// Call this function on button CHECK click!
const check = () => {
// Start a new game if needed
if (isGuessed) start();
// Get the user entered value
// Use parseInt with radix 10 and Math.abs
// to prevent negative numbers
const numUser = Math.abs(parseInt(elNumber.value, 10));
// Do nothing if invalid value entered:
if (!numUser) return;
// Update isGuessed state
isGuessed = numRand === numUser;
// Handle answer:
const textAnswer = `
You guessed: ${numUser}.
The number is ${isGuessed ? "correct!" : numUser > numRand ? "too high." : "too low."}
${isGuessed ? "Congratulations!" : "Try again"}
`;
// Create a LI element with the answer text
const elAnswer = create("li", {
textContent: textAnswer
});
// Append your LI element!
elAnswers.append(elAnswer);
// Clear the current value from input:
elNumber.value = "";
};
// Assign listener to button:
elCheck.addEventListener("click", check);
// Start a new game!
start();
Enter a number from 1 to 10: <input id="number" type="text">
<button id="check" type="button">CHECK</button>
<ol id="answers"></ol>
Additional learning resources:
Arrow_functions (MDN)
Template literals /Template strings (MDN)
Conditional (ternary) operator (MDN)
As I understand it, JavaScript is single-threaded, meaning that it has only one execution thread. Methods like prompt() and alert() block that thread. As long as prompt() is called in a loop, writeln content will not be rendered on the page.
One way to address this with your existing code is to use setTimeout() to delay the next call to prompt(), which allows content to be rendered in the meantime.
That being said, I recommend a more asynchronous method that does not rely on prompt() or writeln(). This answer is intended to explain the issue with your existing code; for a more robust strategy, see Roko's.
var randNum = Math.floor(1 + Math.random() * 999);
function ask() {
let guess = parseInt(window.prompt("Enter a number from 1 to 1000"));
if (guess == randNum) {
document.writeln("<div>Congratulations! You guessed the correct number!</div>");
document.writeln("<div>Your guess: " + guess + ". Actual number: " + randNum + "</div>");
} else if (guess > randNum) {
document.writeln("<div>" + guess + " is Too High. Try Again.</div>");
setTimeout(ask, 50);
} else if (guess < randNum) {
document.writeln("<div>" + guess + " is Too Low. Try Again.</div>");
setTimeout(ask, 50);
}
}
window.addEventListener("load", ask, false);
Essentially what I'm trying to get this to do is display a list of words given by #words on a textarea #display.
Each word is displayed one at a time, delayed by an amount of time designated by getTextSpeed which retrieves speed options chosen by the user.
For example, if the user selects 350 WPM as their desired speed for delay, then each word will have a delay of 117 ms. If they decide to change it to 400 WPM, the delay should decrease in real time dynamically to a delay of 150 ms without having to restart the display animation.
Additionally, if the word contains a character of punctuation, then the delay after the word is displayed should be doubled (ex: 117 ms to 234 ms) and the character should be removed. If there's multiple characters of punctuation, just one should be removed (ex: "..." --> "..")
Below are the relevant methods and my attempt at implementing this behavior.
If you need the rest of the code (for testing purposes?), please see these pastebin links: HTML, Javascript, CSS.
I haven't encountered any errors in the console, but the actual reflected behavior isn't what I want for sure.
There's a lag period at the beginning of starting the animation, which seems to vary based on the length of the input text, and the delay between each word is far, far longer than it should be. Additionally, the punctuation doesn't appear to remove correctly. EDIT #1: I just double-checked the string.remove syntax and you're supposed to put the actual String, not actually call the method from the String superclass.
Please let me know if you need any other information.
var timer;
function start() {
var text = document.getElementById("words").value;
var list = text.split(/\s+/);
runDisplay(list, "display");
}
function runDisplay(data, id) {
var reader = document.getElementById(id);
var index = 0;
var punctDelay = 0;
if (timer) {
clearInterval(timer);
}
if (data.length) {
timer = setInterval(function() {
var punctuation = [".", ",", ":", ";", "!", "?"];
var word = data[index++];
for (var j = 0; j < punctuation.length; j++) {
if (!(word.indexOf(punctuation[j]) === -1)) {
// word = String.replace(punctuation[j], '');
word = word.replace(punctuation[j], ''); // see edit #1
punctDelay = getTextSpeed();
}
}
reader.innerHTML = word;
index = index % data.length;
}, getTextSpeed() + punctDelay); // change speed dynamically in real time
}
}
function stop() {
var display = document.getElementById("display");
clearInterval(timer);
timer = null;
display.innerHTML = "";
}
function getTextSpeed() {
var speeds = document.getElementById("speed");
return speeds.options[speed.selectedIndex].value;
}
I am having a problem with a simple script that is supposed to update a page with some values(user input) that are turned from monthly to yearly (the numbers go into numeric fields created by confirmIT)
<script>
function update() {
for (var i = 0; i < 9; i++) {
var ans = parseInt(document.getElementById("bq10a_" + i).value, 10);
if (!isNaN(ans)) {
var new = ans * 12;
document.getElementById("bq10a_" + i + "calc").value = new;
}
}
}
return;
}
setInterval("update()", 1000);
</script>
this yields an Expected identifier error on line
var new = ans*12;
and i would appreciate any help on how to solve it
The word new is a reserved word in JavaScript and cannot be used as the name of a variable.
The error means that the parser expected an "identifier", which is to say that it expected to see a valid identifier.
Change the name of the variable and things should improve. In the code you've posted I think there's a { } nesting problem; there appears to be one too many before the return of the function.
edit — also as jbabey notes in a comment, your setInterval() call should be
setInterval(update, 1000);
It's not a good idea, generally, to pass strings to setInterval(), despite the advice of thousands of mouldy old instructional websites.
Word "new" -- is special in javascript language:
line is incorrect:
var new = ans*12;
try this:
var newvalue = ans*12;
More information on:
http://javascript.about.com/library/blreserved.htm
http://www.ecma-international.org/publications/standards/Ecma-262.htm
What I want to do is, to make counter of total entered words which will save results even after cleaning text area.
Please take a look at the result of code below: http://jsfiddle.net/mnvMn/5/
NOTE: If you want to fix this problem by changing setInterval(autoPost, 100); DON'T! Because I tested all available change(), paste(), keyUp().... functions. No one of them worked with mobile barcode scanner. Only setting interval works.
var form=$("#bcscanner"), ids=$('#itemids'), counter=0;
function count() {
var value =$(ids).val().replace(" ", "").replace(/[\s,]+$/, '');
var words = value.split(",");
var numWords =words.length;
if($(ids).val() === '') {
numWords = 0;
}
return numWords;
}
function autoPost(){
counter=count()+counter;
$("#counter").html(count()+'/'+counter);
if(count()==="10"){
ajaxpost();
$(ids).val('');
}
}
$(document).ready(function () {
$( "input:submit, input:reset").button();
setInterval(autoPost, 100);
});
Here is a modified version of your fiddle that counts the total words correctly: http://jsfiddle.net/MuyaK/5/
You were updating the global counter on each update instead of tracking the total number of ten word counts.
You can use jQuery plugin to count words, you can restrict typing either by character or words
http://qwertypants.me/counter/
I'm looking for a way to manipulate animation without using libraries
and as usual I make a setTimeout in another setTimout in order to smooth the UI
but I want to make a more accurate function to do it, so if I want to make a 50ms-per-piece
animation, and I type:
............
sum=0,
copy=(new Date()).getMilliseconds()
function change(){
var curTime=(new Date()).getMilliseconds(),
diff=(1000+(curTime-copy))%1000 //caculate the time between each setTimeout
console.log("diff time spam: ",diff)
sum+=diff
copy=curTime
var cur=parseInt(p.style.width)
if (sum<47){//ignore small error
//if time sum is less than 47,since we want a 50ms-per animation
// we wait to count the sum to more than the number
console.log("still wating: ",sum)
}
else{
//here the sum is bigger what we want,so make the UI change
console.log("------------runing: ",sum)
sum=0 //reset the sum to caculate the next diff
if(cur < 100)
{
p.style.width=++cur+"px"
}
else{
clearInterval(temp)
}
}
}
var temp=setInterval(change,10)
I don't know the core thought of my code is right,anyone get some ideas about how to make a more accurate timer in most browser?
Set the JsFiddle url:
http://jsfiddle.net/lanston/Vzdau/1/
Looks too complicated to me, use setInterval and one start date, like:
var start = +new Date();
var frame = -1;
var timer = setInterval(checkIfNewFrame, 20);
function checkIfNewFrame () {
var diff = +new Date() - start;
var f = Math.floor(diff / 50);
if (f > frame) {
// use one of these, depending on whether skip or animate lost frames
++frame; // in case you do not skip
frame = f; // in case you do skip
moveAnimation();
}
}
function moveAnimation () {
... do whatever you want, there is new frame, clear timer past last one
}