var fnr = function (a,b) {
// random integer on closed interval
var y = a + Math.floor((b - a + 1) * Math.random());
return y
}
var foo;
var myTimer;
function toRandom() {
var x = fnr(0, PICTURES.length - 1);
var y = SERVER + FOLDER + PICTURES[x] + SUFFIX;
document.getElementById("img").src = y;
document.getElementById("filename").value = PICTURES[x].toUpperCase();
}
function toRandomize() {
if(!foo) {
foo = true;
document.getElementById("random").value = "stop shuffle";
myTimer = setInterval("toRandom()", 600);
} else {
foo = false;
document.getElementById("random").value = "start shuffle";
clearInterval(myTimer);
}
}
window.onload = function () {
document.getElementById("random").onclick = toRandomize;
}
// button in the body of the HTML portion of my code
<input id="random" type="button" value="start shuffle">
I have a button to randomize photos, but it won't work the second time. Do you guys have any insight in reading the code? I know fnr stands for first-non-repeating, but I'm not too familiar with how to "reset it," or if it requires a reset to get it to work again. I have the same setup for other functions and they work fine.
It's cut so it will only show the parts relevant to the question. I apologize if it's confusing.
Related
I got function within JS which is supposed to show random order divs on btn click.
However once the btn is clicked user got to wait for initial 10 seconds ( which is set by: setInterval(showQuotes, 10000) ) for divs to start showing in random order which is not ideal for me.
JS:
var todo = null;
var div_number;
var used_numbers;
function showrandomdivsevery10seconds() {
div_number = 1;
used_numbers = new Array();
if (todo == null) {
todo = setInterval(showQuotes, 10000);
$('#stop-showing-divs').css("display", "block");
}
}
function showQuotes() {
used_numbers.splice(0, used_numbers.length);
$('.container').hide();
for (var inc = 0; inc < div_number; inc++) {
var random = get_random_number();
$('.container:eq(' + random + ')').show();
}
$('.container').delay(9500).fadeOut(2000);
}
function get_random_number() {
var number = randomFromTo(0, 100);
if ($.inArray(number, used_numbers) != -1) {
return get_random_number();
} else {
used_numbers.push(number);
return number;
}
}
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
Question: How to alter the code so upon the btn click divs will start showing right away without initial waiting for 10 seconds? (take in mind I want to keep any further delay of 10 seconds in between of each div being shown)
Thank you.
Call it when you begin the interval
todo = setInterval((showQuotes(),showQuotes), 10000);
I'm trying to get an image to run two javascript functions at the same time, the problem is that I want the changeImg() function to run continually with each click but only execute the clock() function once. (So that it starts the timer).
<img id="emotion" src="Target.jfif" width="50" onclick="changeImg();clock(); this.onclick=null;"/>
This is my changeImg() script:
{
var x = Math.floor(Math.random()*900);
var y = Math.floor(Math.random()*900);
var obj = document.getElementById("emotion");
obj.style.top = x + "px";
obj.style.left = y + "px";
}
And this is my clock() script:
function clock() {
myTimer = setInterval(myClock, 1000);
var c = 30;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
Have clock() check if the timer is already set, and return.
function clock() {
if (myTimer) { // clock already started
return;
}
myTimer = setInterval(myClock, 1000);
var c = 30;
function myClock() {
document.getElementById("demo").innerHTML = --c;
if (c == 0) {
clearInterval(myTimer);
alert("Reached zero");
}
}
}
instead of passing null to onclick pass the function changeImg
onclick="changeImg();clock();this.onclick=changeImg;"
I don't know about good practices but it works without changing your code too much
I made some HTML code a function so that when a button is clicked it runs randomSong() which is supposed to run a random song right now it runs this:
function randomSong() {
var n = (1 + Math.random() * 2);
if (n == 0){
var song = document.getElementById('1')
console.log("0")
}else if(n == 1){
var song = document.getElementById('2');
console.log('1')}
let y = song
}
var x = y
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
but it doesn't work it says x is not defined anyone now why?
Link to the website I am using this for
I tried your demo it says y is not defined because when you try to access to the outer scope of y.
you can try like so:
var x;
function randomSong() {
var n = (1 + Math.random() * 2);
var song;
if (n === 0){
song = document.getElementById('1')
console.log("0")
}
else if(n === 1){
song = document.getElementById('2');
console.log('1')
}
x = song;
}
function playAudio() {
if(x){
x.play();
}
}
function pauseAudio() {
if(x){
x.pause();
}
}
Yuu need to provide more code if this didn't work. All I did was fix some obviose mistakes. Specifically, n ==enter code here 0 changed to n==0 and var x = y; where y was not a global variable y is now global. If this didn't help add more code and I will see if I can solve it.
var y;
function randomSong() {
var n = (1 + Math.random() * 2);
if (n == 0) {
var song = document.getElementById('1')
console.log("0")
} else if (n == 1) {
var song = document.getElementById('2');
console.log('1')
}
y = song;
}
var x = y;
function playAudio() {
x.play();
}
function pauseAudio() {
x.pause();
}
let, const and class introduced identifiers are block scoped. Hence in
else if(n == 1){
var song = document.getElementById('2');
console.log('1')}
let y = song
}
var x = y
the y variable created by let y = song is not in scope when assigned to x by
var x = y
If the assignment to x proceeds without generating an error it probably means a previous definition of y, possibly with undefined value is in scope. This is a trap that automatically typing can produce:
Don't automatically precede assignments to outer scoped variables with let or const or the assignment won't take place.
let x;
function randomSong() {
const n = (1 + Math.random() * 2);
let song;
if (n === 0) {
song = '0'
console.log("0");
}else if (n === 1) {
song = '1';
console.log('1');
} else {
song = '999';
console.log('999');
}
x = song;
}
function playAudio() {
console.log(`${x} play`);
}
function pauseAudio() {
console.log(`${x} pause`);
}
randomSong();
playAudio();
pauseAudio();
Don't recommend to use var if using of var is unnecessary
i take a look at your site and i noticed when you click on Click Here For Suggesed Song it call function num(), so this show an alert with track suggested. So to turn this to what you want. when we click on button we have to call function randomSong and code with commented explain:
var song = null;
function randomSong() {
//to get audio's number dynamically.
let n = document.querySelectorAll('p audio').length;
//grab all audios from HTML Node List to an array.
let audios = [...document.querySelectorAll('p audio')];
//if there is another song singing ! we should stop it
if(song!==null) song.pause();
//we pick randomly a song inside the array of audios.
song = audios[ Math.floor ( Math.random() * n) ];
//and then we play the song, Enjoy listening!
song.play();
}
Thank you all for you answers but I found a better/eaiser way to do it the javascript is
var songList = [
'mp3_url',
'mp3_url',
'mp3_url',
'mp3_url',
'mp3_url',
];
//this gets a random url from the list
function randomChoice(choices) {
var index = Math.floor(Math.random() * choices.length);
return choices[index];
}
//this is just a place holder you can change this function to anything
function age(){
let current = new Date().getTime();
var myAge = current - 1151560800000;
var myAge = myAge/1000
return myAge;
}
/*this trys to pause x and then play a new song but if x is not defined then you
get an error so you have to do try catch finally*/
function playAudio() {
try{x.pause();}catch(err){
var old = age();
var years = old / 31536000;
console.log('Hello I was ' + old + ' seconds (' + years + ' years) old when you clicked that button!');}finally{
x = randomChoice(songList);
x = new Audio(x);
x.play();
}};
function pauseAudio() {
x.pause();
}
and the HTML is some thing like this
<button onclick="playAudio()">play a song</button>
<button onclick="pauseAudio()">pause the current song</button>
I'm quite new to javascript so the answer is probably quite easy but anyways
I'm trying to make a simple click speed test but i cant get the timer to start when the user presses the click me button, so i resorted to just starting it automatically. if anyone can help me to start it on the button press it will be much appreciated
HTML code:
<button id="click2" onclick="click2()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="10stimer">10s</span>
JS code:
var click = document.getElementById("click2");
var amount = 0;
var seconds = 10;
var endOfTimer = setInterval(click2, 1000);
function click2() {
seconds--;
document.getElementById("10stimer").innerHTML = seconds + "s";
if (seconds <= 0) {
var cps = Number(amount) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("click2").disabled = true;
document.getElementById("10stimer").innerHTML = "Ended";
clearInterval(seconds);
}
}
document.getElementById("click2").onclick = function() {
amount++;
document.getElementById("clicksamount").innerHTML = amount + " Clicks";
}
It looks like you're overwriting your onclick function on the button with id click2 with the lowest 4 lines.
Also, you call clearInterval() with the seconds variable instead of the actual interval, which is referenced by endOfTimer.
I'd suggest to have a separated timer management in a function which you call only on the first click of your button.
See JSFiddle
<button id="clickbutton" onclick="buttonClick()">Click Me!</button><br>
<span id="clicksamount">0 Clicks</span><br><br>
<span id="secondcount">10s</span>
// We will have timerStarted to see if the timer was started once,
// regardless if it's still running or has already ended. Otherwise
// we would directly restart the timer with another click after the
// previous timer has ended.
// timerRunning only indicates wether the timer is currently running or not.
var timerStarted = false;
var timerRunning = false;
var seconds = 10;
var clickAmount = 0;
var timer;
function buttonClick() {
if (!timerStarted) {
startTimer();
}
// Only count up while the timer is running.
// The button is being disabled at the end, therefore this logic is only nice-to-have.
if (timerRunning) {
clickAmount++;
document.getElementById("clicksamount").innerHTML = clickAmount + " Clicks";
}
}
function startTimer() {
timerStarted = true;
timerRunning = true;
timer = setInterval(timerTick,1000);
}
function timerTick() {
seconds--;
document.getElementById("secondcount").innerHTML = seconds + "s";
if (seconds <= 0) {
timerRunning = false;
clearInterval(timer);
var cps = Number(clickAmount) / 10;
document.getElementById("clickbutton").disabled = true;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS (" + clickAmount + "clicks in total)!";
}
}
I made some changes to your code. Effectively, when the user clicks the first time, you start the timer then. The timer variables is null until the first the user clicks.
var click = document.getElementById("click2");
var noOfClicks = 0;
var seconds = 10;
var timer = null;
function doTick(){
seconds--;
if(seconds<=0){
seconds = 10;
clearInterval(timer);
document.getElementById("10stimer").innerHTML= "Ended"
timer=null;
document.getElementById("click2").disabled = true;
}
updateDisplay()
}
function updateClicks(){
if(!timer){
timer=setInterval(doTick, 1000);
clicks= 0;
seconds = 10;
}
noOfClicks++;
updateDisplay();
}
function updateDisplay(){
var cps = Number(noOfClicks) / 10;
document.getElementById("clicksamount").innerHTML = "You got " + cps + " CPS!";
document.getElementById("10stimer").innerHTML =seconds;
}
click.addEventListener('click', updateClicks)
https://jsbin.com/bibuzadasu/1/edit?html,js,console,output
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
Use event listeners rather than onclicks
usage example:
HTML
<button id="mybutton">Click me!</button>
JS
/* ABOVE CODE ... */
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
function timer(startEvent, stopEvent) {
let time = 0;
startEvent.target.addEventListener(startEvent.type, () => {
this.interval = setInterval(()=>{
time++;
}, 10); // every 10 ms... aka 0.01s
removeEventListener(startEvent.type, startEvent.target); // remove the listener once we're done with it.
stopEvent.target.addEventListener(startEvent.type, () => {
clearInterval(this.interval); // stop the timer
// your output function here, example:
alert(time);
removeEventListener(stopEvent.type, stopEvent.target); // remove the listener once we're done with it.
});
});
}
let mybutton = document.getElementById("mybutton");
timer(
{target: mybutton, type: "click"},
{target: mybutton, type: "click"}
);
<button id="mybutton">Click me!</button>
//state initialization
var amount = 0;
var seconds = 10;
var timedOut=false;
var timerId=-1;
//counters display
var clicksDisplay= document.getElementById("clicksamount");
var timerDisplay= document.getElementById("10stimer");
function click2(e){
//first click
if(timerId===-1){
//start timer
timed();
}
//still in time to count clicks
if(!timedOut){
amount++;
clicksDisplay.innerText=amount +" Clicks";
}
}
function timed(){
//refresh timer dispaly
timerDisplay.innerText=seconds+"s";
seconds--;
if(seconds<0){
//stop click count
timedOut=true;
}else{
//new timerId
timerId=setTimeout(timed,1000);
}
}
im searching for a simple way to make a start stop buttons in setInterval function. but when the stop works, the start doesnt...
var zman = 3000;
function pls() {
setTimeout(setInterval, zman);
}
var myVar = setInterval(function() {
var sz;
sz = Math.floor((Math.random() * 750) + 1);
document.getElementById("fsize1").style.fontSize = sz+"%";
console.log(sz);
}, zman);
and
<button onclick="pls()">play</button>
<button onclick="clearInterval(myVar)">Stop</button>
whats wrong? and who can i make a play button when i also want the function to run on the first loading?
In pls() you're asking for setInterval() to be called after 3 seconds. Calling setInterval() with no parameters will do nothing (although there should be an error in your JS console).
You want to define your function once, then call it both when clicked, and at first run:
var zman = 3000,
myVar = null;
function pls() {
if (! myVar)
myVar = setInterval(sizer, zman);
}
function sizer() {
var sz = Math.floor((Math.random() * 750) + 1);
document.getElementById("fsize1").style.fontSize = sz + "%";
console.log(sz);
}
myVar = setInterval(sizer, zman);
<button onclick="pls()">play</button>
<button onclick="clearInterval(myVar); myVar = null;">Stop</button>
<div id="fsize1">test<div>
The line var myVar = setInterval(...) runs as soon as the JavaScript loads. But when the play button is pressed, the setInterval function runs again, but this time without any variable referencing it. So clicking stop would stop the first interval that was started, but since there is no reference to the variable set when clicking play, there is no way to stop it once it gets set.
Try something like this:
var zman = 3000,
myVar,
setFunction = function(){
clearInterval(myVar);
myVar = setInterval(function() {
var sz;
sz = Math.floor((Math.random() * 750) + 1);
document.getElementById("fsize1").style.fontSize = sz+"%";
console.log(sz);
}, zman);
},
clearFunction = function(){
clearInverval(myVar);
};
setFunction();
and
<button onclick="setFunction()">play</button>
<button onclick="clearFunction()">Stop</button>