Second Counter JavaScript, tạo biên điếm tự động tăng trong JavaScript

Thảo luận trong 'Lập trình Javascript, js' bắt đầu bởi seolagi, 8/10/22.

  1. seolagi
    Tham gia ngày:
    16/4/14
    Bài viết:
    1,029
    Đã được thích:
    81
    Điểm thành tích:
    48
    Second Counter JavaScript, tạo biên điếm tự động tăng trong JavaScript nhiều bạn khá cần khi thực hiện hàm về thời gian, và các hàm dữ liệu để chạy hiển thị thông báo cho người dùng thấy là con bao nhiêu thời gian thì hết hạn chẳng hạn.

    Để tạo biến đếm tăng dạng cơ bản, rồi các bạn có thể chế theo mọi cách như sau:

    Second Counter JavaScript

    Cách 1:
    Mã:
    var seconds = 0;
    var el = document.getElementById('seconds-counter');
    function incrementSeconds() {
        seconds += 1;
        el.innerText = "You have been here for " + seconds + " seconds.";
    }
    var cancel = setInterval(incrementSeconds, 1000);
    
    Mã:
    <div id='seconds-counter'> </div>
    Cách 2:
    HTML:
    window.setInterval((function(){
       var start = Date.now();
       var textNode = document.createTextNode('0');
       document.getElementById('seconds').appendChild(textNode);
       return function() {
            textNode.data = Math.floor((Date.now()-start)/1000);
            };
       }()), 1000);
    
    Cách 3: tạo 1 biến đếm giảm từ 5 đến 0 thì dừng lại.
    HTML:
    <button onclick="myFunction()">Try it</button>
    <div id="cscountonoffchat" class="mystyle">5</div>
    <script>
    var seconds = 5;
    var autocount = "";
    var elcountonoffchat = document.getElementById("cscountonoffchat");
    function myFunction() {
      seconds = 5;
      elcountonoffchat.innerText = seconds;
      autocount = setInterval(incrementSeconds, 1000);
    }
    function incrementSeconds() {
        seconds -= 1;
        elcountonoffchat.innerText = seconds;
        if(seconds < 1)
        {
           clearInterval(autocount);
        }
    }
    </script>
    
    • Đếm từ 5 đến 0 dừng lại.
    Gốc: https://stackoverflow.com/questions/37187504/javascript-second-counter
     
    Cảm ơn đã xem bài:

    Second Counter JavaScript, tạo biên điếm tự động tăng trong JavaScript

    Last edited by a moderator: 9/10/22
  2. contraixinh
    Tham gia ngày:
    26/2/23
    Bài viết:
    10
    Đã được thích:
    0
    Điểm thành tích:
    1
    bài viết hay, ý nghĩa thiết thực, ứng dụng thực tế, thanks thớt nhé!
     


Chủ để tương tự : Second Counter
Diễn đàn Tiêu đề Date
Lập trình Javascript, js Disable button and enable it after 5 seconds javascript (khóa button và mở lại sau 5 giây) 8/10/22