As the title says, I think my server can't handle the speed of calculations of the infinite loop, how would I make it so the calculations still go very quick but the server doesn't crash? also when I try this in jsfiddle it eventually crashes my browser.
Here's the code:
<script>
function crashPoint(){
var currentTry = 2;
var mainMultplier = 1;
var secMultiplier = Math.random();
for(;;){
var randomInt = Math.floor(Math.random() * 100) + 1;
if(1/currentTry*100 < randomInt){
currentTry = currentTry+1;
mainMultplier = mainMultplier+1;
}else{
console.clear();
break;
}
}
var totalMultiplier = mainMultplier+secMultiplier;
if(totalMultiplier > 2){
totalMultiplier-1;
}
console.log("Crashed # " + totalMultiplier.toFixed(2));
}
</script>
<button onclick="crashPoint()">
Try me!
</button>
Kind regards.
Have you tried to use setInterval instead of a loop... just call the same function however many times per second you need it to execute.
1/currentTry*100 won't always stay an integer, randomInt will, I just had to make it so randomInt wasn't always an integer anymore which I could do by removing the *100.
Related
how are you?
I am facing some issues with my code running on a snippet.
First: I do not know why when I try to run it, the loop does not finish
Second: One of my friends paste the code and ran on his computer and the loop finish but after running the second time the variables are sum with the new values inserted.
We are all using Google Chrome. Can anyone help me? Thanks.
var i = 0;
var speed = parseInt(prompt('value 1'));
var long = parseInt(prompt('value 2'));
var vel2 = velocidad;
while (speed> 0){
i++;
if (i>speed){
speed--;
}
console.log(speed);
}
sub_i = (i * vel2) - vel2;
console.log('Total i ' + i);
all you need is to initialize i = 0
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))
});
For some time already I'm struggling with following code:
$(document).ready(function(){
keyBind();
});
var set = [];
var start = 0;
var total = 3;
var timeout = 1000;
function displayImages(i, total){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img class="image" src="' + imgPre + i + imgExt +'">';
var sndSrc = new Audio(imgPre + i + sndExt);
var magic = ((i+1)%total) + ',' + total;
sndSrc.play();
pixBox.append(imgSrc);
var sT = setTimeout('displayImages(' + magic + ')', timeout);
set.push(sT);
if(sT >= total+1){
sndSrc.pause();
}
if(sT === total+1){
clearTimeout(sT);
// $('img').remove();
$('img:not(:last-child)').remove();
}
return false;
}
function keyBind(){
$(document).keydown(function(e) {
switch (e.which) {
case 75: //k
displayImages(start, total);
break;
case 80: //p
clearTimeout(set);
break;
default:
return;
}
e.preventDefault();
});
}
It's a kind of very primitive slideshow with accompanying sound files for each picture/slide. As you can see, it's controlled by keyboard input (keyBind function). And it all works fine, but only for the first time. When I trigger it fresh, timeOut function is doing it job and both if statements (first responsible for cutting the sound after the last file, second responsible for wrapping images back to first one after last is displayed) are fireing up and all is well.
That is, until I want to restart the sequence again, without refreshing. If I do that, soundfiles are going mute and the image sequence turns into an endless loop.
I've already tried dividing start and stop of sequence in separate functions, I tried to clear the div and reset the sound at the start of sequence and I did tried reseting the timeOut at the beggining too. All to no avail.
Do you, good and dear people of SO, have any idea what's wrong with my code and can shed some light on it? It's gonna be a lifesaver.
EDIT
It looks like setTimeout(sT) is not working. I've put a console.log after it and sT is not 0, it still has ID of last iteration. What may be the cause? What am I doing wrong?
Some issues:
You use the value that setTimeout returns as if it has some meaning (incremental), but the
actual value is implementation dependent. You should only use it for passing it to clearTimeout,
but not for things like the following:
if(sT >= total+1)
It is also not clear why you would want to add them to the set array,
as only the last one really is pending. All the others have already expired, since you
"chain" calls to setTimeout.
You clear a time-out right after setting one, while there is nothing you did not already know when setting it. So why not avoiding the setTimeout when you would be clearing right after?
Also, the argument to clearTimeout should be a number. It cannot be an array like set:
case 80: //p
clearTimeout(set);
You have a start variable, but ignore it when doing (i+1)%total.
Although not a problem here, you should avoid using strings as arguments to setTimeout, as it is just as evil as eval that way.
Here is a version of your code that fixes several of these issues:
$(document).ready(function(){
keyBind();
});
var sT = -1;
var total = 3;
var timeout = 1000;
function displayImages(i){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img class="image" src="' + imgPre + i + imgExt +'">';
var sndSrc = new Audio(imgPre + i + sndExt);
i = (i+1)%total;
sndSrc.play();
pixBox.append(imgSrc);
if(i == 0){
sT = -1;
sndSrc.pause();
$('img:not(:last-child)').remove();
} else {
sT = setTimeout(displayImages.bind(null, i), timeout);
}
return false;
}
function keyBind(){
$(document).keydown(function(e) {
switch (e.which) {
case 75: //k
displayImages(0);
break;
case 80: //p
clearTimeout(sT);
break;
default:
return;
}
e.preventDefault();
});
}
I am not quite sure when you actually want to stop the sound and remove the images (except one). You might still need to change this code a bit.
EDIT: Adjusted according to correcting comment below:
You should not pass arguments to a function directly using settimeout. This has bugged me out a number of times. See this old post for a solution to this particular part of your code: How can I pass a parameter to a setTimeout() callback?
I'm using NodeJs.
I received constantly request from server.
I'm added some variable like createdTime to it and saved to the database.
when I sorted data by createdTime in some case It is not reliable, It is Repeated
How can I make differentiate between them ?
I do not want to count request.
I do not like to change timestamp's format.
var createdTime = new Date().getTime();
Here's a method of combining a counter with the current time to allow you to have as many as 1000 separate transactions within the same ms that are all uniquely numbered, but still a time-based value.
And, here's a working snippet to illustrate:
// this guarantees a unique time-based id
// as long as you don't have more than 1000
// requests in the same ms
var getTransactionID = (function() {
var lastTime, counter = 0;
return function() {
var now = Date.now();
if (now !== lastTime) {
lastTime = now;
counter = 0;
} else {
++counter;
}
return (now * 1000) + counter;
}
})();
for (var i = 0; i < 100; i++) {
document.write(getTransactionID() + "<br>");
}
If you want something that is likely to work across clusters, you can use process.hrtime() to use the high resolution timer instead of the counter and then make the id be a string that could be parsed into a relative time if needed. Since this requires node.js, I can't make a working snippet here in the browser, but here's the idea:
// this makes a unique time-based id
function getTransactionID () {
var now = Date.now();
var hrtime = process.hrtime();
return now + "." + ((hrtime[0] * 1e9) + hrtime[1]);
}
Due to my low rep I can't add a comment but it looks like you are needing to go beyond milliseconds.Maybe this stackoverflow question can help you
How to get a microtime in Node.js?
I'm working on a JavaScript game that involves throwing a snowball. I need the snowball to render as often as possible during its flight path. Chrome does all the calculations, including setting the style.left and style.top properties, but doesn't actually redraw the snowball until it reaches its destination. Opera doesn't have this problem.
A relevant point is that putting in an alert() after renderSnowball() fixes the problem, except using the alert() is an obvious issue.
Here's my code so far:
function throwSnowball()
{
var theta = parseFloat(angleField.value) * Math.PI/180 ;
var Vir = parseFloat(velocityField.value) ;
if (!isNaN(Vir) && !isNaN(theta) )
{
Vix = Math.cos(theta) * Vir * 50;
Viy = Math.sin(theta) * Vir * 50;
time = new Date() ;
var timeThrown = time.getTime() ;
while (snowballPosY > 0)
{
current = new Date() ;
var currentTime = current.getTime() ;
var timeElapsed = (currentTime - timeThrown)/5000 ;
snowballPosX += Vix * timeElapsed;
snowballPosY += Viy * timeElapsed;
Viy -= GRAVITY * timeElapsed ;
renderSnowball() ; //renderSnowball() sets the style.left
// and style.top properties to snowballPosX pixels
// and snowballPosY pixels respectively
timeThrown = currentTime ;
}
snowballPosX = 0 ;
snowballPosY = 50 ;
renderSnowball() ;
}
}
You're totally blocking the main thread. Have you tried using a setTimeout (even with a zero timeout) to allow other things to happen during your animation?
If you're willing to use experimental technology, requestAnimationFrame would be even better.
Edit: the setTimeout approach would look something like this (replacing the while loop):
var drawAndWait = function() {
if (snowballPosY > 0) {
// movement/drawing code here
setTimeout(drawAndWait, 20 /* milliseconds */);
} else {
// reset code that would normally go after your while loop
}
};
drawAndWait();
So each time the drawing finishes, it arranges for itself to be invoked again, if appropriate. Note that your throwSnowball function will return quickly; the throwing isn't actually done until later on. This takes awhile to get used to doing correctly; don't be too concerned if it's not intuitive at first.
Try getting out of the tight loop. Chrome may not want to redraw until your function exits. Try using setInterval or setTimeout to give Chrome a chance to repaint.