每x秒重复一次代码,但如果[在这里插入检查]则不重复 [英] Repeat code every x seconds but not if [insert check here]

查看:93
本文介绍了每x秒重复一次代码,但如果[在这里插入检查]则不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题的跟进,我找到了如何使代码每隔x秒重复一次。是否有可能制作一个可以改变这种情况的活动?即我有一个复选框,用于控制是否重复,所以我想我需要这样的东西:

This is a followup to this question, where I found out how to make code be repeated every x seconds. Is it possible to make an event that can change this? I.e. I have a checkbox which is meant to control whether this is repeated or not, so I figured I'd need something like this:

$(checkbox).bind("change", function() {
    switch(whether if it is ticked or not) {
        case [ticked]:
            // Make the code repeat, while preserving the ability to stop it repeating
        case [unticked]:
            // Make the code stop repeating, while preserving the ability to start again
    }
});

我不知道我能把什么放在案例中 s。

I have no idea what I could put in the cases.

推荐答案

function fooFunc() {
    $('#foo').text(+new Date());
}
var id;
var shouldBeStopped = false;
$('input').change(function() {
    if (shouldBeStopped) 
        clearInterval(id);
    else 
        id = setInterval(fooFunc, 200);

    shouldBeStopped = !shouldBeStopped;
});​

直播演示

这篇关于每x秒重复一次代码,但如果[在这里插入检查]则不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆