How to stop loop after specific number? - javascript

I need the auto click to stop after 320 times.
How to do it?
var = "320";
// i need the loop to stop after 320 times.
var button = document.getElementById("jsonp2");
setInterval(function() {
button.click();
}, 10000);
<input type="button" id="jsonp2" href="javascript:void(0)" onclick="javascript:alert('button autoclicked');" class="btn refreshListButton" title="Refresh">

You need to use the clearInterval function
http://jsfiddle.net/pdmafjpa/71/
var iterations = 5;
var count = 0;
var button = document.getElementById("jsonp2");
var myInterval = setInterval(function(){
if (count >= iterations) {
clearInterval(myInterval);
} else {
count++;
button.click();
}
}, 2000);

var i=1;
function a(){
if(i<320)
{
console.log(i);
setTimeout(a,1000);
i++;
}}
a();

Related

How to stop and resume an interval instead of clearing and recall it?

I got this interval function which adds + 1 every second to this element, and a button which stops it with clearInterval(), but i want to "stop" and "resume" the interval instead of "clear" and restarting it. For example if the interval was stopped with 700 miliseconds, so i want to resume it for runnig from these 700 miliseconds and not from 0.
How can i do that?.
var testingB = $('#testing');
var testingBox = $('.text3');
var counter = 0;
var checker = null;
setInterval( function () { testingBox.text(counter); },1);
var id = setInterval( function () { counter++; },1000);
function adder() {
if (checker === null ) {
clearInterval (id);
checker = true;
testingB.text('Keep Counting');
}
else {
id = setInterval( function () { counter++; },1000);
checker = null;
testingB.text('Stop Couting');
};
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="testing" onclick="adder()"> Stop Counting </button>
<p class="text3"> </p>

Show elements of array one by one - Jquery

So I have a button on which I want to display each element of my array for a few seconds. This is my html code:
<button class="btn" id="random">Start</button>
I have made an array with jQuery that I want to use to change the buttons text:
$(document).ready(function() {
$("#random").on("click", loop);
});
var array = ["el1","el2","el3"];
function loop() {
for (i = 0; i < array.length; i++) {
$("#random").html(array[i]);
}
var random = Math.floor(Math.random() * array.length) + 1;
$("#random").html(array[random]);
}
The for loop is supposed to do what I want but I can't find a way to delay the speed, it always just shows the last line of code. When I try setTimeout or something it just looks like it skips the for loop.
My proposal is to use IIFE and delay:
var array = ["el1","el2","el3", "Start"];
function loop(){
for (i = 0; i < array.length; i++){
(function(i) {
$("#random").delay(1000).queue(function () {
$(this).html(array[i]);
$(this).dequeue();
});
})(i);
}
}
$(function () {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>
Basically, a for loop will not help you. It runs with the max speed it can. And delaying it would do no good in js (you would just freeze the browser). Instead, you can just make a function that will execute itself with a delay. Kinda recursion, but not entirely. Below would make the trick.
https://jsfiddle.net/7dryshay/
$(document).ready(function() {
$("#random").on("click", function (event) {
// texts to cycle
var arr = ["el1","el2","el3"];
// get the button elem (we need it in this scope)
var $el = $(event.target);
// iteation function (kinda recursive)
var iter = function () {
// no more stuff to display
if (arr.length === 0) return;
// get top of the array and set it on button
$el.text(arr.shift());
// proceed to next iteration
setTimeout(iter, 500);
}
// start first iteration
iter();
});
});
Use setInterval() and clearInterval()
$(document).ready(
function() {
$("#random").on("click", loop);
}
);
var array = ["el1", "el2", "el3"];
var int;
function loop() {
var i = 0; // variable for array index
int && clearInterval(int); // clear any previous interval
int = setInterval(function() { //store interval reference for clearing
if (i == array.length) clearInterval(int); // clear interval if reached the last index
$("#random").text(i == array.length ? 'Start' : array[i++]); // update text with array element atlast set back to button text
}, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn" id="random">Start</button>
UPDATE : If you need to implement it using for loop and setTimeout() then do something like this
var array = ["el1", "el2", "el3", "Start"];
function loop() {
for (i = 0; i < array.length; i++) {
(function(i) {
setTimeout(function() {
$("#random").html(array[i]);
}, i * 1000);
})(i);
}
}
$(function() {
$("#random").on("click", loop);
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<button class="btn" id="random">Start</button>

How to make my script pause after reaching a certain condition for 1000ms

I've got a setInterval script that repeats logging "Hello world" 10 times.
I would like to make it stop for 1 second after repeating 10 times, then starting again and doing the process for ever.
here is what I have:
var i = 0;
var x = setInterval(function(){
console.log("Hello world");
i++;
if(i >= 10){
i = 0;
stopInterval()
}
},1000);
var stopInterval = function(){
clearInterval(x);
setTimeout(function(){
//restart the interval, but how do I do???
},1000);
};
However, it says stopInterval is not defined and I thought it was
So you need to use clearInterval and use the id that is returned from setInterval to clear it.
function myTimer() {
var i = 0,
interval = setInterval(function(){
console.log("Hello world");
i++;
if(i >=10){
clearInterval(interval);
window.setTimeout(myTimer, 1000);
}
},100);
}
https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers
just with setTimeout and Recursion DEMO
var i = 1;
var delay = 500;
function callMe() {
console.log("Hello World"+i);
document.getElementById("pri").innerHTML = "Hello World " + i;
if (i == 11) {
i = 1;
delay = 1000;
console.log("......Restart");
document.getElementById("pri").innerHTML = "......Restart";
} else {
delay = 300;
}
setTimeout(callMe, delay);
++i;
}
window.onload = callMe;
<div id="pri"></div>

jQuery/JavaScript: Initiate and terminate a loop with the same button

I want to build a button that when I click it, the function in JavaScript associated with it initiates (so a loop inside it start doing something).
If I click it again before the loop inside the function finishes, the loop will terminates.
If I click it again after the loop inside the function has already finished, the loop will just start as usual.
How do I do this with the following code?
Thanks in advance.
HTML:
<button id="startstop" class="btn btn-primary" onclick="count()">
JavaScript:
function count() {
var val = 0;
var loop = setInterval(function(){
val++;
if (val > 1000} {
clearInterval(loop);
}
}, 100);
}
try this code
var loop;
function count() {
var val = 0;
if (loop) {
clearInterval(loop);
loop = null;
}
else{
loop = setInterval(function(){
val++;
console.log(val);
if (val > 1000) {
clearInterval(loop);
loop = null;
}
}, 100);
}
}
I'm not a big fan of doing work for people, but on this occasion I'll succumb...
You need to store the internal ID outside of the function, and base your process on that. If the ID is not set, start the interval, if it is set stop the interval.
Note, that I've massively reduced the length of interval, and the number of times it fires for this example...
var _intervalId = -1;
function count() {
if (_intervalId == -1) {
var val = 0;
_intervalId = setInterval(function(){
val++;
if (val > 200) {
clearInterval(_intervalId);
_intervalId = -1
document.getElementById("output").innerHTML = "stopped automatically";
}
}, 10);
document.getElementById("output").innerHTML = "started";
} else {
clearInterval(_intervalId);
_intervalId = -1;
document.getElementById("output").innerHTML = "stopped manually";
}
}
<button onclick="count();return false">Click Here</button>
<div id="output"></div>
Place loop variable in global scope and everytime the user clicked stop previous loop if it's already started if not start it.
Hope this helps.
var loop=null;
count = function () {
var val = 0;
//Stop previous loop if it's already started
if(loop!=null){
clearInterval(loop);
loop=null;
}else{
loop = setInterval(function(){
val++;
console.log(val);
$('span').text(val);
if (val >= 20) {
clearInterval(loop);
}
}, 100);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="startstop" class="btn btn-primary" onclick="count()">Count</button>
<span>0</span>
I had fun building a small class for this. Feel free to use.
// Counter class
function Counter(callback, speed, max, init){
var loop = null;
this.callback = callback;
this.value = init || 0;
this.max = max;
function count(){
if (this.max && this.value >= this.max) {
clearInterval(loop);
loop = null;
} else {
this.value++;
}
this.callback(this.value);
}
this.start = function(){
if(!this.isStarted){
loop = setInterval(count.bind(this), speed);
}
};
this.stop = function(){
if(this.isStarted){
clearInterval(loop);
loop = null;
}
}
Object.defineProperty(this, "isStarted", { get: function(){
return !!loop;
}});
}
// Usage example.
var result = document.getElementById("counter");
var button = document.getElementById("startstop");
// Create the counter and the callback.
var counter = new Counter(function(val){
result.innerHTML = val;
}, 100, 1000);
// Init the result value.
result.innerHTML = counter.value;
// Listen for click events on the button.
button.addEventListener("click", function(){
if(counter.isStarted){
counter.stop();
} else {
counter.start();
}
});
<div id="counter"></div>
<button id="startstop">Toggle</button>

The javascript for the time increases it's speed on the second loop

Help me debug this code. The button should open a link onclick and the visit button on the main page will be disabled and it's value will become a timer. There's no problem on first click, but when the timer runs out and I click the button again, the speed of the clock increases. Please help me.
<html>
<head>
<script type = "text/javascript">
var t;
var isTimeron = false;
var counter = 0;
function disableButt()
{
document.getElementById("but1").disabled = true;
}
function enableVisit()
{
document.getElementById("but1").disabled = false;
}
function stopMe()
{
isTimeron = false;
clearTimeout(t);
}
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
function startMe() {
if (!isTimeron)
{
counter = 10;
isTimeron = true;
countdown();
}
}
</script>
<body>
<a href='' target = '_blank'><input type = "button" id = "but1" value = "VISIT" style="background:#83FF59; font-weight:bold;"
onclick = "startMe(); disableButt();"/></a>
</body>
</html>
You are not stopping the first timer.
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
The counter goes under zero, you call stopMe() by you still call setTimeout. You have two timer going on now.
Just change it to
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
return;
}
t = setTimeout("countdown();", 1000);
}
Small suggestion avoid strings in setTimeout.
setTimout(countdown, 1000);
is better

Categories