Javascript: How to disable a button instantly? [duplicate] - javascript

This question already has an answer here:
How to disable a button with a timed loop?
(1 answer)
Closed 9 years ago.
Attack = attack button.
When I run this code (click on the button), it takes about 1 second to disable the button. How can I set this up to disable instantly? I'm assuming it's because of the 1000 ms timer, but i'm not sure.
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 0;
function disabledTimer() {
if (start > 5){
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
blitz.disabled = true;
start++;
};
}

yes, it's because of the 1000ms timer. if you set it to 10 it will take 10 ms to disable. if you need it to start disabled, move (or copy) the blitz.disabled = true code out of the interval callback:
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 1; // set to 1 to maintain consistency (i.e. call blitz.disabled = true the same amount of times as the original code.
blitz.disabled = true;
function disabledTimer() {
if (start > 5) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
blitz.disabled = true;
start++;
}
}
if you need to do more complex stuff and this code is just an example, you can wrap your complex statements inside a function and call it from outside and inside the interval:
var disabledStartTimer = setInterval(disabledTimer, 1000);
var start = 1; // set to 1 to maintain consistency (i.e. call blitz.disabled = true the same amount of times as the original code.
function disableBlitz() {
blitz.disabled = true;
}
disableBlitz();
function disabledTimer() {
if (start > 5) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
blitz.disabled = false;
}
else {
disableBlitz();
start++;
}
}

set the timer to 0
var disabledStartTimer = setInterval(disabledTimer, 0);
or simply call
disabledTimer();

Set this:
var disabledStartTimer = setInterval(disabledTimer, 1000); // 1 sec
To this:
var disabledStartTimer = setInterval(disabledTimer, 0); // 0 sec
As the time is counted here in Milliseconds. You can be sure of this, it really is because of the setInterval.

Related

How to stop timer and check for value if value is not met continue and else stop timer and do something

So like the title says i have this timer and i would like that once that it reaches 0, it should check if a variable called "user_energy" in this case is equal to 100. If it is than the timer will stop, and it could do something. Like for example just a console.log("It works") and if its not then it should repeat itselfs.
How would you be able to do something like that?
This is the code:
function startTimer() {
var interval = 10000;
{
localStorage.endTime = +new Date + interval;
}
if(!localStorage.endTime)
{
startTimer();
}
setInterval(function()
{
var remaining = localStorage.endTime - new Date;
if( remaining >= 0 )
{
$('#energytimer').text( Math.floor( remaining / 1000 ) );
} else
{
startTimer();
}
}, 100);
}
It's a little unclear how the localStorage stuff fits into the question, but here's a simple countdown timer that does what you are asking. You can adapt this to store the counter in localStorage if that's what you want to do.
The key is to assign a variable to the return value from the timer so that you can call clearTimeout() and pass that variable and stop the timer later.
let timer = null; // <-- This will hold a reference to the timer
var counter = 5;
timer = setInterval(function(){
if(counter === 0){
clearTimeout(timer); // Stop the timer
console.log("Times up!");
} else {
$("#energytimer").text(counter--);
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="energytimer"></div>

setInterval for stopwatch

I'm trying to make a stopwatch. Here's the code:
var min = 0, sec = 0, censec = 0
$("#startBtn").on("click", function() { // when start button is clicked
$(this).hide(); // start is hidden
$("#stopBtn").show(); // stop is shown
setInterval(add, 10); // the censec will be increased every 10 millisecond.
$("#censec").text(censec);
})
function add() {
censec++;
if (censec == 100) {
censec = 0;
sec++;
if (sec == 60) {
sec = 0;
min++;
}
}
}
The problem is that setInterval() happens only at once. The censec only changes from 00 to 1. That's it.
P.S. I'm new to coding, so if there are other mistakes, please don't hesitate to tell me.
The setInterval calls to add will definitely repeat. But your code is only ever showing the value of censec once, when you start the timer.
If you want to update the display every hundredth of a second, put the code showing the value in add.
Separately, the code as it is in the question won't run at all, because it has a ReferenceError on the first line. Those ; should be ,.
Example (this also stores the timer's handle and clears the timer when you click the stop button):
var min = 0, sec = 0, censec = 0;
// Note ---^--------^
function add() {
censec++;
if (censec == 100) {
censec = 0;
sec++;
if (sec == 60) {
sec = 0;
min++;
}
}
$("#censec").text(censec);
}
var timer = 0;
$("#startBtn").on("click", function() { //when start button is clicked
$(this).hide(); //start is hidden
$("#stopBtn").show(); //stop is shown
timer = setInterval(add,10); //the censec will be increased every 10 millisecond.
});
$("#stopBtn").on("click", function() {
clearInterval(timer);
timer = 0;
$(this).hide();
$("#startBtn").show();
});
<input type="button" id="startBtn" value="Start">
<input type="button" id="stopBtn" value="Stop" style="display: none">
<div id="censec"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that although it may be mostly fine to use setInterval for displaying, using it to track the elapsed time is a bad idea; it frequently doesn't fire precisely.
Instead, record when you started
var start = Date.now();
...and then when the timer fires, figure out how long it's been since you started
var elapsed = Date.now() - start;
Then use the value (milliseconds) in elapsed to figure out your display.
Your variable declarations have ; instead of , .
Also checking numbers on equality should be done by using === but that is not the problem here.
Your also not updating the view in your timer. So updating of your html should also be in your function that is called by the timer.
If the goal is to use real seconds and milliseconds, I also suggest using the Date type because your timer will be late and not real-time. So still use the timer with the interval you like but in the add function you call the date object. You can replace the 3 vars for one datetime of type Date which will give you the granularity that you like.
var dateTimeStart = null, censecElement = null, timer = null;
$("#startBtn").on("click", function() {//when start button is clicked
$(this).hide(); // start is hidden
$("#stopBtn").show(); // stop is shown
if(timer === null) {
// timer was not started
dateTimeStart = new Date();
timer = setInterval(updateCensec, 10); //the censec will be increased every 10 millisecond.
console.log("Started timer");
}
});
$("#stopBtn").on("click", function() {//when stop button is clicked
$(this).hide(); // stop is hidden
$("#startBtn").show(); // start is shown
if(timer) {
// timer is started/running
clearInterval(timer);
console.log("Stopped timer");
}
timer = null;
});
function updateCensec() {
var sensec = 0, sec = 0, dateTimeNow = new Date(), diffMilliseconds = 0;
diffMilliseconds = dateTimeNow - dateTimeStart;
censec = parseInt((diffMilliseconds % 600 ) / 10); // convert milliseconds to centi seconds
sec = parseInt(diffMilliseconds / 600);
if(censecElement === null) {
censecElement = $("#censec");
}
censecElement.text(sec + ":" + censec);
}
I would like to suggest that you do not update your view every 10 milliseconds even if you want your stopwatch to show time in centiseconds.

I need a solution for a gambling script

I have a script for a gambling site.
What I need is that after 2 calls to the function multiply, it bets the maximum stake possible and after that calls the function reset, I mean in each two sequential loss it bets the full balance in my account reset for the minimum stake and continue playing, Because I realized that in odds of 1.1 on 'manual bet' in each 2 loss the next will be a won.
It is like: after 2 multiplyCalls bet the full balance (it is the "MAX" button in the image below) and reset the game to continue playing. Am I being clear enough?
I tried to create a function for this but did not work
The "Maximum stake" button element code is:
MAX
this is the printscreen
The part of the script I want to modify is this, the multiplyCalls function is already created. I changed the var multiply = (current * 2).toFixed(8); to var multiply = (current * 1).toFixed(8); because my strategy does not have martingale.
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 2).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
reset();
console.log('=== RESETING ===');
}
}
This is the full script:
var startValue = '0.00000001', // Don't lower the decimal point more than 4x of current balance
stopPercentage = 0.001, // In %. I wouldn't recommend going past 0.08
maxWait = 500, // In milliseconds
stopped = false,
stopBefore = 3; // In minutes
multiplyCalls = 0; // <--- Added this global
var $loButton = $('#double_your_btc_bet_lo_button'),
$hiButton = $('#double_your_btc_bet_hi_button');
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 1).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
reset();
console.log('=== RESETING ===');
}
}
function getRandomWait(){
var wait = Math.floor(Math.random() * maxWait ) + 100;
console.log('Waiting for ' + wait + 'ms before next bet.');
return wait ;
}
function startGame(){
console.log('Game started!');
reset();
$loButton.trigger('click');
}
function stopGame(){
console.log('Game will stop soon! Let me finish.');
stopped = true;
}
function reset(){
$('#double_your_btc_stake').val(startValue);
}
// quick and dirty hack if you have very little bitcoins like 0.0000001
function deexponentize(number){
return number * 1000000;
}
function iHaveEnoughMoni(){
var balance = deexponentize(parseFloat($('#balance').text()));
var current = deexponentize($('#double_your_btc_stake').val());
return ((balance*2)/100) * (current*2) > stopPercentage/100;
}
function stopBeforeRedirect(){
var minutes = parseInt($('title').text());
if( minutes < stopBefore )
{
console.log('Approaching redirect! Stop the game so we don\'t get redirected while loosing.');
stopGame();
return true;
}
return false;
}
// Unbind old shit
$('#double_your_btc_bet_lose').unbind();
$('#double_your_btc_bet_win').unbind();
// Loser
$('#double_your_btc_bet_lose').bind("DOMSubtreeModified",function(event){
if( $(event.currentTarget).is(':contains("lose")') )
{
console.log('You LOST! Multiplying your bet and betting again.');
multiply();
setTimeout(function(){
$loButton.trigger('click');
}, getRandomWait());
//$loButton.trigger('click');
}
});
// Winner
$('#double_your_btc_bet_win').bind("DOMSubtreeModified",function(event){
if( $(event.currentTarget).is(':contains("win")') )
{
if( stopBeforeRedirect() )
{
return;
}
if( iHaveEnoughMoni() )
{
console.log('You WON! But don\'t be greedy. Restarting!');
reset();
if( stopped )
{
stopped = false;
return false;
}
}
else
{
console.log('You WON! Betting again');
}
setTimeout(function(){
$loButton.trigger('click');
}, getRandomWait());
multiplyCalls = 0; // reset value
}
});startGame
So basically, you want to max the bet after two losses. Because multiply calls only occur after a loss, we can assume that the if(multiplyCalls < 2) bit takes care of that. So in the following else, all you really need to do is hit max bet instead of call reset(). Based on what I understand the code to be doing, this should be sufficient, correct?
function multiply(){
if(multiplyCalls < 2){ // test multiply
var current = $('#double_your_btc_stake').val();
var multiply = (current * 1).toFixed(8);
$('#double_your_btc_stake').val(multiply);
multiplyCalls++; // increment
}else{
//reset(); /* instead of resetting here, let's max the bet. */
$('#double_your_btc_max').trigger('click');
console.log('=== RESETING ===');
}
}

setting a one minute timer in JavaScript memory aid game

<div id="counter">1:00</div>
function countdown() {
var secs = 60;
function tick() {
var counter = document.getElementById("counter");
secs--;
counter.innerHTML = "0:" + (secs < 10 ? "0" : "") + String(secs);
if( secs > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game Over");
}
}
tick();
}
countdown(60);
I am having a problem with this portion of my game. I'm trying to set a 60 seconds timer for the game that starts at 60 and ends at 0, when it gets to 0 the game stops and an alert shows that the game is over.
I am very new to programming, so please give me as many feedbacks as you can. I found this code on the internet, and I figured out most of it, could you also tell me what does the tick() function do over here?
Here is one way you can do it:
First declare a variable you will use for an interval (should be 'global', attached to window):
var countDownInterval = null;
Then, a function to trigger the tick interval, you should call this whenever the game is ready to start:
function startCountDown()
{
countDownInterval = setInterval(tick,1000); //sets an interval with a pointer to the tick function, called every 1000ms
}
which will call the tick function every second:
function tick()
{
// Check to see if the counter has been initialized
if ( typeof countDownInterval.counter == 'undefined' )
{
// It has not... perform the initialization
countDownInterval.counter = 0; //or 60 and countdown to 0
}
else
{
countDownInterval.counter++; //or --
}
console.log(countDownInterval.counter); //You can always check out your count # the log console.
//Update your html/css/images/anything you need to do, e.g. show the count.
if(60<= countDownInterval.counter) //if limit has been reached
{
stopGame(); //function which will clear the interval and do whatever else you need to do.
}
}
and then the function where you can do everything you need to do after game has finished:
function stopGame()
{
clearInterval(countDownInterval);//Stops the interval
//Then do anything else you want to do, call game over functions, etc.
}
You can fire up the counter at any time by calling startCountDown();
Pseudo code of tick:
function tick() {
reduce counter variable;
if counter > 0
wait for 1 second; (This is what setTimeout(tick, 1000) means)
call tick() again (recursively)
}
else {
game over
}
}
Something like this?
var countdown = function(sec, tick, done) {
var interval = setInterval(function(){
if(sec <= 0) {
clearInterval(interval);
done();
} else {
tick(sec)
sec--;
}
}, 1000)
}
countdown(10, console.log, function(){console.log('done')})

Plain JS countdown with repeat and delay

I keep running into several issues when creating a countdown script
it does not run smoothly
hard to make it repeat (closure)
hard to delay the start and to delay the repeat (closure)
Can someone please help me FIX this code which should work in my opinion but doesn't
the processing I need is
a. counter starts delay number of seconds after the page loads,
b. when counter reaches 0, the countdown RE-starts after delay number of seconds
Here is my Fiddle
Issues:
when it starts, the counter seems to wait an additional second before counting down
it does not pause
the repeat starts after the counter has continued
.
// more accurate timer - https://gist.github.com/1185904
function interval(duration, fn){
this.baseline = undefined
this.run = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if(nextTick<0){
nextTick = 0
}
(function(i){
i.timer = setTimeout(function(){
i.run(end)
}, nextTick)
}(this))
}
this.stop = function(){
clearTimeout(this.timer)
}
}
window.onload=function() {
var cnt1 = 10;
var delay1 = 5;
var timer1 = new interval(1000, function(){
document.getElementById('out1').innerHTML=cnt1--
if (cnt1 <= 0) { // trying to reset
timer1.stop(); // does not work
cnt1 = 10;
setTimeout(function() { timer1.run()},delay1*1000)
}
})
setTimeout(function() { timer1.run()},delay1*1000)
}
I've rewritten your code to produce the desired results. Your previous code was very inefficient. See my script comments for usage.
Fiddle: http://jsfiddle.net/RVBDQ/1/
/*
#name timer
#param number startFrom Starts counting down from this number
#param number delay Seconds to wait before repeating the counter
#param number intervalDelay Milliseconds between countdown
#param number runTimes Optional; Limit of counting. The function stops when it has run <runTimes> times. Default 1 (=one countdown)
#param Boolean noFirstRun Optional; If false, the counter starts off immediately. Default false
*/
function timer(startFrom, delay, intervalDelay, runTimes, notFirstRun){
if(typeof runTimes == "undefined") runTimes = 1;
if(runTimes-- < 0) return;
setTimeout(function(){
var ctn = startFrom;
var timer1 = window.setInterval(function(){
document.getElementById('out1').innerHTML = ctn--;
if(ctn <= 0){
clearInterval(timer1);
timer(startFrom, delay, intervalDelay, runTimes, true);
}
}, intervalDelay);
}, notFirstRun?delay*1000:0);
}
window.onload=function() {
timer(10, 5, 1000, 2);
//Runs two times, starts counting from 10 to 1, delays 5 seconds between counters.
}
Object exposing start([delay]) and stop().
http://jsfiddle.net/RVBDQ/3/
function interval(duration, fn, delay){
this.timer = null;
this.duration = duration;
this.fn = fn;
this.start(delay);
}
interval.prototype.start = function(delay){
if (this.timer) {return;}
var self=this;
this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
var self = this,
nextTick = called ? this.duration - (new Date - called) : 0;
this.timer = setTimeout(function(){
self.fn();
self.run(new Date);
}, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
clearTimeout(this.timer);
this.timer = null;
};
window.onload = function() {
var cnt1 = 10;
var delay1 = 5;
window.timer1 = new interval(1000, function(){
document.getElementById('out1').innerHTML=cnt1;
cnt1 = cnt1 === 1 ? 10 : cnt1-1;
}, delay1*1000);
};

Categories