2017-01-19 2 views
0

HTML код:функция времени не работает

<body class="body" onload="buttonFunction(this)"> 
    <form> 
     <p align="center"><strong>You have been on this page for </strong><input title="time spent on webpage" type="text" size="9" name="timespent"></p> 
    </form> 
</body> 

JS код:

function buttonFunction() { 
    startday = new Date(); 
    clockstart = startday.getTime(); 
    initstopwatch(); 
    getSecs(); 
} 


function initstopwatch() { 
    var mytime = new Date(); 
    var timeNow = mytime.getTime(); 
    var timediff = timeNow - clockstart; 
    this.diffsecs = timediff/1000; 
    return(this.diffsecs); 
} 

function getSecs() { 
    var mySecs = initstopwatch(); 
    var mySecs1 = ""+mySecs; 
    mySecs1= mySecs1.substring(0,mySecs1.indexOf("."))+ " secs. "; 
    document.forms[0].timespent.value = mySecs1; 
    window.setTimeout('getSecs()',1000); 
} 

Теперь эта функция должна подсчитать количество секунд, пользователь находится на моем веб-страницу и ввод этой переменной в поле ввода. Однако, похоже, ничего не делает. Так в чем проблема с этой функцией?

+0

Ваша переменная clockstart должна быть глобальной. Вы вызываете 'initstopwatch' 2 раза подряд. Ваш код вызывает «SyntaxError», потому что у вас есть invalide ';' здесь: 'window.setTimeout ('getSecs()', 1000;)'. – GramThanos

+0

Я исправил это. – GameCoder

+0

@ThanasisGrammatopoulos Я пытаюсь создать функцию buttonfunction() как глобальную функцию, к которой может идти любая функция, получить необходимые входные данные, а затем продолжить работу. Это возможно? – GameCoder

ответ

0

Итак, давайте начнем с самого начала, потому что я смогу объяснить больше вещей таким образом.

Сначала нам нужно сэкономить время, когда пользователь прибыл на страницу. Мы можем сделать это, сохранив дату после загрузки страницы.

// The variable is outside because we need every function to 
// be able to access it (like a global variable) 
var userArrived; 

// The function to initialize the counter 
function initCounter(){ 
    // Get the date when the user arrived 
    // here we do not use `var` because the variable exists 
    userArrived = new Date().getTime(); // This returns the date in milliseconds 
} 

// Wait the page to load  
window.addEventListener('load', function(){ 
    // Initialize the counter 
    initCounter(); 
}, false); 

Теперь нам нужна функция, чтобы дать нам разницу

function getCounterValue(){ 
    // Calculate difference 
    var value = new Date().getTime() - userArrived; 
    // This variable now have the time the user 
    // is on the page in milliseconds 

    // Now we need to return the value to the caller 
    return value; 
} 

Теперь, когда мы можем получить миллисекунды нам нужна функция для разбора их в удобочитаемый формат.

function parseMs2Sec(ms){ 
    // We calculate seconds using seconds = milliseconds/1000 
    // but we round it so that we don't have decimals 
    var sec = Math.round(ms/1000); 
    // Now we need to return the value to the caller 
    return sec; 
} 

Осталось только обновить любой визуальный элемент, который нам нужен каждые 1 сек (или более).

// Save the element on a variable for easy access 
var timeSpent = document.forms[0].timespent; 

// Update the screen with the latest time 
function updateScreeenCounter(){ 
    // Get the time the user is in the page 
    var ms = getCounterValue(); 
    // Convert it to seconds 
    var sec = parseMs2Sec(ms); 

    // Display it in the page 
    timeSpent.value = sec + " sec."; 
} 

// Every 1000 milliseconds 
setInterval(function(){ 
    // Run function 
    updateScreeenCounter(); 
}, 1000); 
// But this last code (with the interval) 
// needs to run after the counter was initialized 
// so we should put it inside the onload event we created. 

А вот код отверстие в демке:

// 
 
    // The variable is outside because we need every function to 
 
    // be able to access it (like a global variable) 
 
    var userArrived; 
 

 
    // The function to initialize the counter 
 
    function initCounter(){ 
 
     // Get the date when the user arrived 
 
     // here we do not use `var` because the variable exists 
 
     userArrived = new Date().getTime(); // This returns the date in milliseconds 
 
    } 
 

 
    // Gives back the time since the user arrived on page (in ms) 
 
    function getCounterValue(){ 
 
     // Calculate difference 
 
     var value = new Date().getTime() - userArrived; 
 
     // This variable now have the time the user 
 
     // is on the page in milliseconds 
 
     
 
     // Now we need to return the value to the caller 
 
     return value; 
 
    } 
 

 
    // Converts the given ms in the closest seconds 
 
    function parseMs2Sec(ms){ 
 
     // We calculate seconds using seconds = milliseconds/1000 
 
     // but we round it so that we don't have decimals 
 
     var sec = Math.round(ms/1000); 
 
     // Now we need to return the value to the caller 
 
     return sec; 
 
    } 
 

 
    // Update the screen with the latest time 
 
    function updateScreeenCounter(){ 
 
     // Get the time the user is in the page 
 
     var ms = getCounterValue(); 
 
     // Convert it to seconds 
 
     var sec = parseMs2Sec(ms); 
 
     
 
     // Display it in the page 
 
     document.forms[0].timespent.value = sec + " sec."; 
 
    } 
 

 
    // Wait the page to load  
 
    window.addEventListener('load', function(){ 
 
     // Initialize the counter 
 
     initCounter(); 
 
     // Every 1000 milliseconds 
 
\t  setInterval(function(){ 
 
\t   // Run function 
 
\t   updateScreeenCounter(); 
 
\t  }, 1000); 
 
    }, false);
<form> 
 
    <input name="timespent" value="Loading ..."/> 
 
</form>

еще несколько советов:

  1. Читать снова Javascript учебник здесь w3schools
  2. Прочитайте руководство Chrome Devtools здесь DevTools (Firefox и Opera имеет такую ​​же функциональность тоже)

~~~ ~~~ Редактировать

Я забыл упомянуть, что лучше использовать setInterval в этом потому что он более точен, чем рекурсивный setTimeout на медленном компьютере.

1

Комментарий от Пер Танасиса Грамматопулоса, мой предыдущий ответ (ниже) был неправильным. Я попытался запустить ваш код, установив точку с запятой, и работает в Safari.

window.setTimeout('getSecs()',1000;) 

должен быть

window.setTimeout('getSecs()',1000); 

мой предыдущий неправильный ответ: SetTimeout только собирается вызвать getSecs() один раз. Я думаю, что вы хотите назвать это один раз в секунду, а не один раз в одну секунду, в этом случае вы должны использовать:

window.setInterval(getSecs,1000); 

Если вы хотите, чтобы остановить интервал позже (вероятно, хорошая идея), вы можете просто сделать:

var interval = window.setInterval(getSecs,1000); 

и позже, когда вы хотите, чтобы остановить таймер, просто вызовите:

clearInterval(interval); 
+0

'getSecs' будет называть его через 1 секунду, а затем снова ... – GramThanos

+0

А, правда. Угадайте, что это просто синтаксическая ошибка: window.setTimeout ('getSecs()', 1000;) вместо window.setTimeout ('getSecs()', 1000); – thmsdnnr

+0

переменная 'clockstart' имеет значение null внутри' initstopwatch'; – GramThanos

0

в принципе, setTimeout должен быть г помещается с setInterval (как вы хотите, чтобы getSecs вызываться несколько раз не один раз). Затем, что вы должны пройти к нему, это ссылка на функцию, а не на ее вызов, поэтому getSecs (без кавычек или скобок), а не "getSecs()". И это, скорее всего, причина. Я не могу проверить код сейчас. Проблема, однако, в том, что getSecs() не называть себя, как это будет до setInterval

Во-вторых, код заслуживает огромный очистки, но я буду в состоянии предложить больше помощи завтра, если никто не придумал хороший реорганизовать.

+0

Я использую webstorm, поэтому рефакторинг должен быть простым. Если я знаю, что делать с этой функцией. – GameCoder

Смежные вопросы