Итак, давайте начнем с самого начала, потому что я смогу объяснить больше вещей таким образом.
Сначала нам нужно сэкономить время, когда пользователь прибыл на страницу. Мы можем сделать это, сохранив дату после загрузки страницы.
// 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>
еще несколько советов:
- Читать снова Javascript учебник здесь w3schools
- Прочитайте руководство Chrome Devtools здесь DevTools (Firefox и Opera имеет такую же функциональность тоже)
~~~ ~~~ Редактировать
Я забыл упомянуть, что лучше использовать setInterval
в этом потому что он более точен, чем рекурсивный setTimeout
на медленном компьютере.
Ваша переменная clockstart должна быть глобальной. Вы вызываете 'initstopwatch' 2 раза подряд. Ваш код вызывает «SyntaxError», потому что у вас есть invalide ';' здесь: 'window.setTimeout ('getSecs()', 1000;)'. – GramThanos
Я исправил это. – GameCoder
@ThanasisGrammatopoulos Я пытаюсь создать функцию buttonfunction() как глобальную функцию, к которой может идти любая функция, получить необходимые входные данные, а затем продолжить работу. Это возможно? – GameCoder