S
S
Sergey Sulakov2015-11-23 18:31:45
PHP
Sergey Sulakov, 2015-11-23 18:31:45

JavaScript code optimization. How is it better?

The bottom line is this: PHP generates a set of numbers on the server, for example:

$numbers = array('+1','+6','-4','+3','+4','-1','+7','+2','-5','+1','-2','+5','-4','+2');

Further on the page, you need to play it in this format - every second a new digit appears and is accompanied by an audio file (voicing of this number), at the end the visitor needs to enter the total answer.
The problem arises in the following:
How to do it in the best way?
At the moment it is implemented like this:
foreach($numbers as $index => $number){?>
  interval = setTimeout(function() {
        $("#number").html("<?=$number?>");//Показ слагаемого
        sound.play('peek')//Озвучивание
    }, <?=(3800+($index*1000))?>);
<?}

And it turns out that if there are 100 numbers, then there will be 100 intervals.
How can I write this in a javascript loop or something?
And question 2: how in JavaScript to make a continuous display of a random number with a change of the same number every second?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stalker_RED, 2015-11-23
@web-verzus-team

Let's display all the numbers so that they can be picked up in js

<span id="numbers" style="display: none;"><?=implode(',', $numbers)?></span>
<pre id="display">start</pre>

(function(){
    var numbers = document.querySelector('#numbers').innerHTML.split(','), // распарсим числа
        delay = 1000, // задержка между цифрами, msec
        len = numbers.length,
        counter = 0,
        display = document.querySelector('#display'),
        timer = setInterval(function(){ // запустим таймер
            if (counter < len) { // если еще не добрались до конца массива
                display.innerHTML = numbers[counter++]  // выводим число
            } else {
                clearInterval(timer) // или выключаем таймер
                display.innerHTML = 'end!'
            }
        }, delay)
    })()

Demo: jsfiddle.net/Stalk/1dat8qmq/1
UPD : for the second question: use setInterval() and Math.random()

A
Alexander Taratin, 2015-11-23
@Taraflex

https://developer.mozilla.org/en-US/docs/Web/Guide...
https://developer.mozilla.org/en-US/docs/Web/Event...
https://github. com/kriskowal/q (for convenience only)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question