jquery 添加“随机”内容以从当前时间开始每秒值

jquery Add "random" stuff to value every second from current time?

本文关键字:时间 开始 添加 随机 jquery      更新时间:2023-09-26

我很小。 对此有点无知。我已经设法通过我的span标签中的javascript/jquery获取当前时间。这是实现我真正意图的开始。

想要一个脚本,该脚本在 10 秒(从我当前获得的时间开始)的时间内每秒将一定的数字(0 到 5 之间)添加到我在类的 span 类中的当前值.value。 我知道有点令人困惑,但我会尝试以这种方式描述它:

强调当前时间是30/9/2013 - 10:38:47

在十秒钟内,函数将添加 0 到 5 范围内的随机值

1st second - time: 30/9/2013 - 10:38:47 - adds: +3 - displays: 103
2nd second - time: 30/9/2013 - 10:38:48 - adds: +1 - displays: 104
3th second - time: 30/9/2013 - 10:38:49 - adds: +5 - displays: 109
4th second - time: 30/9/2013 - 10:38:50 - adds: +0 - displays: 109
5th second - time: 30/9/2013 - 10:38:51 - adds: +2 - displays: 111
6th second - time: 30/9/2013 - 10:38:52 - adds: +4 - displays: 115
...(up to)...
10th second - time: 30/9/2013 - 10:38:56 - adds: +2 - displays: 133
and now from beggining..

我不知道如何做这样的事情,所以我需要一些帮助,起点或其他东西

目前我的项目只有两个跨度并显示当前时间:http://jsfiddle.net/a76wa/

.html:

<span class="value">100</span>
</br>
<span class="new-time"></span>

脚本:

var currentdate = new Date();
var datetime = currentdate.getDate() + "/" + (currentdate.getMonth()+1)  + "/" + currentdate.getFullYear() + " - " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
$(".new-time").text(datetime);

任何帮助或建议不胜感激。

我认为这就是你要找的:http://jsfiddle.net/jonigiuro/Q6wpu/

var startVal = $('.value');
var newTime = $('.new-time');
var startLink = $('.start');
startLink.on('click', function() {
    var tracker = 0; //varialbe to count the passed seconds
    var startValue = parseInt(startVal.text()); //get the start value
    var t = setInterval(function() {
        tracker++; //add 1 each second
        var randomNumber = Math.round(Math.random() * 10); //generate a random integer between 0 and 10
        startValue += randomNumber; //add the start value and the random number
        newTime.text(startValue); //change the text
        if(tracker === 10) { //after ten seconds
           clearInterval(t); //stop the timer
            startVal.text(startValue); //and change the start value
        }
    }, 1000);
});

您需要单击"启动计数器"才能启动

使用SetInterval()函数来执行逻辑,只需将每秒随机秒数添加到当前时间的函数中:

setInterval(function() {
      // Do something every second
}, 1000);