How do i stop this code from executing using a stop button - javascript

I have a start button which triggers a function.
<button type="button" onclick="start()">START</button>
Here is my java script
function start() {
var cookieValue = document.getElementById('balance').getAttribute('value');
if (cookieValue == 0){
alert("insufficient funds");
exit();
}else{
var url = $("#url").val() + '.php?check=';
console.log(url);
var line = $("#ccs").val();
var linesend = line.split("\n");
linesend.forEach(function(value, index) {
setTimeout(
function start() {
Array.prototype.randomElement = function () {
return this[Math.floor(Math.random() * this.length)]
}
$.ajax({
url: url + value,
type: 'GET',
async: true,
success: function(result) {
if (result.match("success")) {
removeline();
live(result);
}else {
removeline();
dead(result);
}
}
});
},2500 * index);
});
}
}
How do I stop this 2500 * index loop right here using a stop function? Cause I wanted a stop button for this one

Clear timeout?
var timeout = setTimeout(start, 2500*index);
clearTimeout(timeout);

Related

location.reload(true); not working in ie11

i have a script that reload the page when the value is >= 100 the problem is that location.reload(true); are not working in ie11, i also have tried with window.location = self.location.href; but i am having the same problem, in other browsers it works good.
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
}, 2000);
}
});
You don't appear to have defined self anywhere, so you may have an error there. Beyond that, you're trying to assign the value of href as the whole value of location - which is meant to be an object. Instead, try:
window.location.href = window.location.href;
Try to move the if statement into the success callback.
Like that you can clear the interval into the same stack and reload the page on the good
.
$(function() {
if (value < 100) {
var timer = setInterval(function() {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function(msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value)
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
window.location = self.location.href;
}
},
error: function(err) {
clearInterval(timer);
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});
place the if in the success function, ajax is asynchronous the if will execute immediately but value will change after the ajax has completed so the code may never reach the if statement
$(function () {
if (value < 100) {
var timer = setInterval(function () {
$.ajax({
type: "GET",
url: $("#ancUrl").attr('href'),
data: {},
success: function (msg) {
console.log("This is msg:" + msg);
var msgInt = parseInt(msg);
if (msgInt > value) {
value = msgInt;
$("#progress-bar").width(value.toString() + "%");
if (value >= 100) {
clearInterval(timer);
location.reload(true);
}
}
},
error: function (err) {
console.log(err.responseText);
},
dataType: "json"
});
}, 2000);
}
});

Compare data returned from AJAX with div data

I would like to compare data to determine if the div needs to be reloaded.
// <![CDATA[
$(function () {
function reload (elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache : false,
url : '/inbox-header.php',
type : 'get',
success : function (data) {
var result = $.trim(data);
var resu = $.trim($original);
console.log(result);
if (result == resu) {
alert('a');
setTimeout(function () {
reload(elem, interval)
}, interval);
return;
}
$elem.html(data);
setTimeout(function () {
reload(elem, interval)
}, interval);
}
});
}
reload('#inboxheader', 500);
});
// ]]>
When I show the output in the console it looks the same, but the alert never shows, so its always false.
UPDATE:
The output of those variables can be found here, unable to post them here..
http://pastebin.com/abfCk7pH
I dont know why but the trim function did not do his job.
this works:
$(function() {
function reload(elem, interval) {
var $elem = $(elem);
var $original = $elem.html();
$.ajax({
cache: false,
url: '/inbox-header.php',
type: 'get',
success: function(data) {
var opgehaaldedata = data.replace(
/(\r\n|\n|\r)/gm, "");
var orgineledata = $original.replace(
/(\r\n|\n|\r)/gm, "");
if (opgehaaldedata == orgineledata) {
//alert('a');
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
} else {
$elem.html(opgehaaldedata);
setTimeout(function() {
reload(elem, interval)
}, interval);
return;
}
}
});
}
reload('#inboxheader', 500);
});

Clear setTimeouts applied by class.each operation that creates timeout

I'm sorry the title might not make much sense. I'm not sure how to word what i'm doing.
I have a class that I add to elements that uses HTML5 data attributes to setup a refresh timer. Here is the current code.
$(document).ready(function () {
$('.refresh').each(function() {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var preloader = element.data('show-loading');
var globalPreloader = true;
if (typeof preloader === 'undefined' || preloader === null) {
}
else if (preloader != 'global' && preloader != 'true') {
globalPreloader = false;
}
(function(element, url, interval) {
window.setInterval(function () {
if (!globalPreloader)
{
$('#' + preloader).show();
}
$.ajax({
url: url,
type: "GET",
global: globalPreloader,
success: function (data) {
element.html(data);
if (!globalPreloader) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
})(element, url, interval);
});
$.ajaxSetup({ cache: false });
});
Now I have elements that a user can click on the 'window' which removes it.
These elements can be tired to a timer that was set by the above code.
Code used to remove the element
$(".btn-close").on('click', function () {
var id = $(this).closest("div.window").attr("id");
if (typeof id === 'undefined' || id === null) {
} else {
$('#' + id).remove();
}
});
I need to now kill the timers created for the elements removed.
What is the best way to do this?
Not clear on how you clear them so I do them all here at the end.
$(document).ready(function () {
$('.refresh').each(function () {
var element = $(this);
var url = element.data('url');
var interval = element.data('interval');
var showLoading = element.data('show-loading');
var preloaderID = element.data('preloader-id');
if (typeof showLoading === 'undefined' || showLoading === null) {
showLoading = true;
}
(function (element, url, interval) {
var timerid = window.setInterval(function () {
if (showLoading) {
$('#' + preloaderID).show();
}
$.ajax({
url: url,
type: "GET",
global: showLoading,
success: function (data) {
element.html(data);
if (showLoading) {
$('#' + preloaderID).hide();
}
}
});
}, interval);
element.data("timerid",timerid );//add the timerid
})(element, url, interval);
});
$.ajaxSetup({
cache: false
});
$('.refresh').each(function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
});
Example: remove timer on a click
$('.refresh').on('click', function () {
var timerId = $(this).data("timerid");
window.clearInterval(timerId);
});
window.setIntervalreturns a handle for the timeout. You can use that to stop the timeout:
var handle = window.setInterval(function() {
window.clearInterval(handle);
}, 1000);
Hope that helps.
Here's a little demo of intervals and "interval assassins". It's a minimal example showing how you can clear intervals in a JavaScript-y way.
$('.start').click(function() {
var $parentRow = $(this).closest('tr')
var $stop = $parentRow.find('.stop')
var $val = $parentRow.children('.val')
// interval
var iid = setInterval(function() {
$val.text(+$val.text() + 1)
}, 10)
console.log(`New Target: ${iid}`)
// interval assassin
$stop.click(function() {
clearInterval(iid)
console.log(`Interval[${iid}] has been assassinated.`)
$(this).off('click')
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</tr>
<tr>
<td><button class="start">Start</button></td>
<td><button class="stop">Stop</button></td>
<td class="val">0</td>
</table>
Just run the snippet to see a demo. Feel free to comment if you have any questions. You can set up multiple intervals by pressing start repeatedly and have them all be cleared at once with a single click of stop.

On click of button, check if user is logged in or not

I have a button that is responsible for performing multiple task, and has lot of scripting for it. When this button
<button type="submit" value="submit" name="submit" class="second_button">Negotiate</button>
the script applied on this button is
<script>
var startClock;
var submitamt;
var walkaway;
var digits;
$(function() {
startClock = $('#startClock').on('click', onStart);
submitamt = $('#submitamt').on('click', onSubmit);
walkaway = $('#walkaway').on('click', onWalkAway);
digits = $('#count span');
beforeStart();
});
var onStart = function(e) {
startClock.fadeOut(function() {
startTimer();
submitamt.fadeIn(function() {
submitamt.trigger('click'); // fire click event on submit
});
walkaway.fadeIn();
});
};
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
console.log(returndata[3]);
// $('#proddisplay').html(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
var onWalkAway = function(e) {
console.log('onWalkAway ...');
};
var counter;
var timer;
var startTimer = function() {
counter = 120;
timer = null;
timer = setInterval(ticker, 1000);
};
var beforeStart = function() {
digits.eq(0).text('2');
digits.eq(2).text('0');
digits.eq(3).text('0');
};
var ticker = function() {
counter--;
var t = (counter / 60) | 0; // it is round off
digits.eq(0).text(t);
t = ((counter % 60) / 10) | 0;
digits.eq(2).text(t);
t = (counter % 60) % 10;
digits.eq(3).text(t);
if (!counter) {
clearInterval(timer);
alert('Time out !');
resetView();
}
};
var resetView = function() {
walkaway.fadeOut();
submitamt.fadeOut(function() {
beforeStart();
startClock.fadeIn();
});
};
</script>
before this script executes i wish to check if the user is logged in or not, In normal php i use this code
<?
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true || isset($_SESSION['fb_logged_in']) && $_SESSION['fb_logged_in'] == true )
{?>
<!--display message-->
<?}?>
but i am not able to understand how to embed it with the script i wish to display a popup message if the user is not logged in and ask user to login first
it is not recommended to check it with client side scripting. try it with hidden variable..
<input type="hidden" name="userLog" id="userLog" value="<?=$_SESSION['fb_logged_in'];?>">
and in script check
if($('#userLog')!=''){
// do something..
}
Embed the Session check in the http post. Return an error code (for example 400) when not logged in and process popup handling in the error function.
<?
if (isset($_SESSION['loggedin'])
&& $_SESSION['loggedin'] == true || isset($_SESSION['fb_logged_in'])
&& $_SESSION['fb_logged_in'] == true ) {?>
<!-- display message -->
<?}else{
http_response_code(400);
}?>

JS/Ajax: Submit form without page refresh or button click

I am trying to submit a form without a button click or page refresh. Once the form is submitted then I will echo the value in the input field through php. The problem is that I added a timer but is not doing anything at all. How can i set a timer once user stops typing give two seconds(keyup) and then take the value? EXAMPLE
JS
<script>
$(function() {
var timer;
$(".submit").click(function() {
$('submit').on('keyup', function() {
var name = $("#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "index.php",
data: dataString,
success: function(result){
/*$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();*/
$('#special').append('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
});
}, 2000;
});
</script>
PHP
<?php
if($_POST){
$url = $_POST['name'];
echo ('<b><span id="resultval">'.$url.'</span></b>');
}
?>
http://jsfiddle.net/earlonrails/pXA6U/2/
$(function() {
var timer = null;
var dataString;
function submitForm(){
alert("success");
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
alert("success");
}
});
return false;
}
$('#submit').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
var name = $("#name").val();
dataString = 'name='+ name;
});
});
​
I use the following to provide an auto-refreshing page with a visual timer. It does more than you need, but it could be stripped back to something simpler.
Launch it at page load with
auto_refresh();
Supporting functions below
/**
* This function checks if the auto-refresh check box is checked and then refreshes the page.
*
*
*/
function auto_refresh() {
// ****************************************
// Countdown display
// ****************************************
$("#countdown").progressbar({ value: 100 });
check_refresh(120, 120);
$("#autorefresh").click(function() {
if ($(this).attr("checked") == "checked") {
$("#countdown").progressbar("option", "disabled", false );
$("#countdown").progressbar("option", "value", 100);
check_refresh(120, 120);
}
});
}
And...
/**
* This functions sets the time interval used to auto-refresh the page.
*/
function check_refresh(countdownValue, secondsRemaining) {
var autorefresh = $("#autorefresh");
if ($(autorefresh).attr("checked") == "checked") {
setTimeout(function() {
var value = Math.round(secondsRemaining / countdownValue * 100);
// consoleDebug("Seconds remaining: " + secondsRemaining);
secondsRemaining -= 10;
$("#countdown").progressbar("option", "value", value);
if (secondsRemaining < 0) {
loadDashboard(); // <--- Launch whatever you want here.
check_refresh(120, 120);
} else {
check_refresh(countdownValue, secondsRemaining);
}
}, 10000);
} else {
$("#countdown").progressbar({ disabled: true });
}
}

Categories