简体   繁体   English

如何只在网页上运行一次间隔? (jquery)

[英]How can I run the interval on my webpage only once? (jquery)

I have a webpage: 我有一个网页:

<textarea class="form-control" rows="5" id="textArea" name='textArea' maxlength="250" style="resize:none" placeholder=""></textarea>
<small>
    <span id="counter"></span>
</small>

and a jquery binded to this: 和一个jQuery绑定到此:

$('#textArea').bind('input propertychange', function () {
    display30Seconds();
});


function display30Seconds() {
    var validTime = 30000;
    counterInterval = setInterval(function () {
        $('#counter').html(validTime / 1000);
        validTime = validTime - 1000;
    }, 1000);
}

I want a simple effect - when user starts typing in the text area, he sees the counter going down from 30 to 0. When the counter goes down to zero I want to display an alert and disable text area. 我想要一个简单的效果-当用户开始在文本区域中键入内容时,他看到计数器从30下降到0。当计数器下降到零时,我想显示一个警报并禁用文本区域。 So far it works bad, because each time user types anything in text area - then we start another counters and they overlay. 到目前为止,它的效果很差,因为每次用户在文本区域中键入任何内容时,我们都会启动另一个计数器并将它们覆盖。 How can I fix it? 我该如何解决? http://jsfiddle.net/jf4ea4nx/ http://jsfiddle.net/jf4ea4nx/

I want a simple effect - when user starts typing in the text area, he sees the counter going down from 30 to 0. When the counter goes down to zero I want to display an alert and disable text area. 我想要一个简单的效果-当用户开始在文本区域中键入内容时,他看到计数器从30下降到0。当计数器下降到零时,我想显示一个警报并禁用文本区域。

Check the comments in the code below 检查以下代码中的注释

Demo 演示版

 $('#textArea').on('input propertychange', display30Seconds); // Define the variable var interval; function display30Seconds() { var validTime = 3000; // Changed for Demo purpose // If timer not already started if (!interval) { // Save the interval id interval = setInterval(function() { $('#counter').html(validTime / 1000); validTime = validTime - 1000; // When timer reaches zero if (validTime < 0) { // Clear the interval clearInterval(interval); alert('Time Up!'); // Disable textarea $('#textArea').prop('disabled', true); } }, 1000); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <textarea class="form-control" rows="5" id="textArea" name='textArea' maxlength="250" style="resize:none" placeholder=""></textarea> <small><span id="counter"></span></small> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM