簡體   English   中英

如何使用JavaScript為數組中的每個項目設置唯一變量?

[英]How can I set unique variable foreach item in array with javascript?

我想為每個數字設置一個時間戳,然后針對其自身測試每個數字的時間戳。

        var timestamp;
        nums=["1", "2", "3"];
        nums2=nums.map(myFunction);


        function myFunction(num) {

          setInterval(function() {

            var current_time = Math.floor(Date.now() / 1000);

            if (typeof timestamp !== "undefined" ) {
                if (current_time > (timestamp + 60)) {
                    timestamp = Math.floor(Date.now() / 1000);
                    console.log('time stamp reset');
                } else {
                    console.log('time stamp too young will reset after 60 sec');
                }
            } else {
                timestamp = Math.floor(Date.now() / 1000);
                console.log('time stamp set');
            }

         }, 10000);

        }

****如果我運行腳本20秒鍾:****

當前輸出:

time stamp set

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

*(10 seconds later)*

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

所需的輸出:

time stamp set

time stamp set

time stamp set

*(10 seconds later)*

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

time stamp too young will reset after 60 sec

我不明白您要在這里做什么,所以我的回答完全基於您的當前輸出所需的輸出

您的timestamp變量是在global范圍內聲明的,因此,第一次調用myFunction ,其值是undefined ,但在后續調用中,它將保留一些值,從而導致“當前輸出”。

要解決此問題,請在myFunction移動timestamp變量。

 nums=["1", "2", "3"]; nums2=nums.map(myFunction); function myFunction(num) { var timestamp; setInterval(function() { var current_time = Math.floor(Date.now() / 1000); if (typeof timestamp !== "undefined" ) { if (current_time > (timestamp + 60)) { timestamp = Math.floor(Date.now() / 1000); console.log('time stamp reset'); } else { console.log('time stamp too young will reset after 60 sec'); } } else { timestamp = Math.floor(Date.now() / 1000); console.log('time stamp set'); } }, 10000); } 

使用函數生成器和setInterval

 const data = []; //populate data for(let i = 0; i < 3; i++){data.push(i)} function * gen(){ const timestamp = Date.now(); let currentTimestamp; do{ currentTimestamp = yield Date.now(); }while(currentTimestamp - timestamp < 60000); return; } function run(){ let iter = gen(); let t = null; let i = 0; const res = []; const si = setInterval(function(){ const {done,value} = iter.next(t); if(done){ console.log("60 seconds have gone... reseting...") iter = gen(); //reseting i = res.length = 0; } t = value; if(i >= data.length){ console.log("waiting..."); return; } console.log("Set timestamp"); const d = [data[i], value]; console.log(d); res[i++] = d; }, 1000); } window.onload = run; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM