javascript - Simulate click on all radio buttons and loop continuously - Stack Overflow

ScenarioI currently have 3 radio buttons that I want to be clicked every 2 seconds. This would keep cyc

Scenario

I currently have 3 radio buttons that I want to be clicked every 2 seconds. This would keep cycling through over and over until I hit the "Stop" button.

HTML

<div id="gen">
    <input type="radio" id="radio1" name="radios" />
    <input type="radio" id="radio2" name="radios" />
    <input type="radio" id="radio3" name="radios" />

    <div id="genBtn">
        <button type="button" id="stopBtn">Stop</button>
    </div>
</div>

JavaScript

$(document).ready(function() {

    /* Every 2 seconds, click each radio button */
    var rollDemRadios = setInterval(function() {
        $('input[name="radios"]').each(function() {
            // You can only see the last one clicked after about 3 seconds
            $(this).click();
        });
    }, 2000);

    /* Stops the radio buttons from rolling */
    $('#stopBtn').click(function() {
        clearInterval(rollDemRadios);
    });
});

Visual Representation

•(click) • •

• •(click) • // after 2 seconds

• • •(click) // another 2 seconds, then click the first one again

[Stop]

Fiddle: /

Issues

Why can I only see the last radio button being clicked instead of "each radio button every 2 seconds"?

Also, how do I continuously loop through all 3 radio buttons (after last radio button is clicked, start over to the 1st one)?

Attempts

  • Enclosed $(this).click() with a setTimeout() or setInterval() to make clicking visible to the user's eye.
  • Added a while(true) inside the setInterval() to loop continuously. Not smart, but was worth a try!

Scenario

I currently have 3 radio buttons that I want to be clicked every 2 seconds. This would keep cycling through over and over until I hit the "Stop" button.

HTML

<div id="gen">
    <input type="radio" id="radio1" name="radios" />
    <input type="radio" id="radio2" name="radios" />
    <input type="radio" id="radio3" name="radios" />

    <div id="genBtn">
        <button type="button" id="stopBtn">Stop</button>
    </div>
</div>

JavaScript

$(document).ready(function() {

    /* Every 2 seconds, click each radio button */
    var rollDemRadios = setInterval(function() {
        $('input[name="radios"]').each(function() {
            // You can only see the last one clicked after about 3 seconds
            $(this).click();
        });
    }, 2000);

    /* Stops the radio buttons from rolling */
    $('#stopBtn').click(function() {
        clearInterval(rollDemRadios);
    });
});

Visual Representation

•(click) • •

• •(click) • // after 2 seconds

• • •(click) // another 2 seconds, then click the first one again

[Stop]

Fiddle: http://jsfiddle/3xeyf/5/

Issues

Why can I only see the last radio button being clicked instead of "each radio button every 2 seconds"?

Also, how do I continuously loop through all 3 radio buttons (after last radio button is clicked, start over to the 1st one)?

Attempts

  • Enclosed $(this).click() with a setTimeout() or setInterval() to make clicking visible to the user's eye.
  • Added a while(true) inside the setInterval() to loop continuously. Not smart, but was worth a try!
Share Improve this question edited May 5, 2014 at 14:53 Marlo C asked May 5, 2014 at 14:44 Marlo CMarlo C 6173 gold badges15 silver badges26 bronze badges 4
  • Please add your code in the question as well. If the jsfiddle URL goes down, no one has an idea what your code is. – Flater Commented May 5, 2014 at 14:45
  • @Flater Okay, will do! – Marlo C Commented May 5, 2014 at 14:46
  • 1 Why? Because ever 2 seconds, you loop through all the 3 radio buttons, and you get to see only the end result, which is the last one being clicked. – KBN Commented May 5, 2014 at 14:51
  • Thank you for all the responses! I will try each answer and give a +1 for working code (if only I can give +0.5 for effort). I'll find which answer is the simplest and most efficient to implement. – Marlo C Commented May 5, 2014 at 15:42
Add a ment  | 

6 Answers 6

Reset to default 2

The problem is in how your code is set up. To explain:

var rollDemRadios = setInterval(function() {
    $('input[name="radios"]').each(function() {
        $(this).click();
    });
}, 2000);

Let's take away the middle bit, just to simplify things.

var rollDemRadios = setInterval(function() {
    DoYourWork();
}, 2000);

So, what happens in this snippet? Much like you would expect, every 2 seconds, the browser will run the DoYourWork() method. Suppose that it shows you an alert box. That means you will be presented with an alert box every 2 seconds.

But you weren't displaying an alert box. What you are doing is this:

    $('input[name="radios"]').each(function() {
        $(this).click();
    });

What does this do? For each button found, it clicks it. Very simply put:

    firstRadioButton.click();
    secondRadioButton.click();
    thirdRadioButton.click();

Let's call this action "Click three buttons sequentially". I'll use this name later on.

Will the code wait between those three click events? No. Why not? You didn't ask it to. You only asked it to wait after having clicked all three buttons.

This is basically what happens:

  • First interval
  • "Click three buttons sequentially". Notice that there is no time set between the three clicks. Those buttons will be clicked as fast as your browser can do it.
  • waiting for two seconds...
  • Second interval (two seconds after the first one)
  • "Click three buttons sequentially". Notice that there is no time set between the three clicks. Those buttons will be clicked as fast as your browser can do it.
  • and so on...

You cannot perceive the three buttons being clicked, because the browser is much faster than your eyes. What you need to do is tell the browser to wait after clicking each button. In your current example, you are telling it to wait after clicking all buttons. That's the root cause of your issue.

This should space the clicks evenly, waiting 2 seconds per click rather than per batch of clicks:

var radiobuttons = $('input[name="radios"]');
var i = 0;

var rollDemRadios = setInterval(function() {
    var currentbutton = radiobuttons[i];

    currentbutton.click();

    i = (i + 1) % radiobuttons.length; //0, then 1, then 2, then 0, then 1, then 2, then 0, ...

}, 2000);

Try

$(document).ready(function () {

    var index = 0,
        $inps = $('input[name="radios"]'),
        len = $inps.length;
    /* Every 2 seconds, click each radio button */
    var rollDemRadios = setInterval(function () {
        $inps.eq(++index % len).click();
    }, 2000);

    $inps.first().click();

    /* Stops the radio buttons from rolling */
    $('#stopBtn').click(function () {
        clearInterval(rollDemRadios);
    });
});

Demo: Fiddle

You can keep track of witch radio is next to be clicked using a variable

$(document).ready(function() {
    var current = 0;
    /* Every 2 seconds, click each radio button */
    var rollDemRadios = setInterval(function() {
        $('input[name="radios"]').eq(current).click();
        if (current == 2) { current = 0; } else { current ++; }
   }, 2000);

    /* Stops the radio buttons from rolling */
    $('#stopBtn').click(function() {
        clearInterval(rollDemRadios);
    });
});

Fiddle

This should work:

http://jsfiddle/3xeyf/7/

$(document).ready(function() {
    var rdoIndex = 0;    
    /* Every 2 seconds, click each radio button */
    var rollDemRadios = setInterval(function() {
        var rdoCount = $('input[name="radios"]').length;
        $('input[name="radios"]:eq(' + rdoIndex%rdoCount + ')').click();
        rdoIndex++;        
    }, 2000);

    /* Stops the radio buttons from rolling */
    $('#stopBtn').click(function() {
        clearInterval(rollDemRadios);
    });
});

Here you keep track of the currently clicked radio button and do that index modulus the count of radio buttons in total to continually loop over indexes 0-2.

Please try the following code in your $document.ready(function(){ });

var i=0;    
var rollDemRadios = setInterval(function() {
    if(i===3)
    {
        i=0;
    }
    $('input[name="radios"]:eq('+i+')').click();
    i++;
}, 2000);

/* Stops the radio buttons from rolling */
$('#stopBtn').click(function() {
    clearInterval(rollDemRadios);
});

Regards

Just put setTimeout logic

var i = 0;
var stop = false;
$(document).ready(function() {
 CheckRadio();
$("#stopBtn").click(function(){
    stop = true;
});

});

function CheckRadio()
{if(!stop){
$($("input[type='radio']")[i]).click();
i +=1;

setTimeout(function(){
     if(i > 2) i =0;
     CheckRadio();

},2000);
}
}

Fiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745213172a4616964.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信