2017-01-19 6 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); 
} 

は、この機能は、ユーザーが自分のWebページや入力その変数上での秒数をカウントすることになっています入力ボックスに入力します。しかし、何もしないようです。では、この関数の問題は何ですか?

+0

あなたの 'clockstart'変数はグローバルでなければなりません。 'initstopwatch'を連続して2回呼び出します。 invalide ';'ここに 'window.setTimeout( 'getSecs()'、1000;)'があるため、あなたのコードは 'SyntaxError'をスローします。 – 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. ここにクロームデベロッパーツールガイドを読むDevTools私はこの中でsetIntervalを使用することをお勧めしていることを言及するのを忘れてしまった

~~~編集~~~

(FirefoxとOperaは同じ、あまりにも機能があります)低速のコンピュータでは再帰的なものよりも正確です。

1

Per Thanasis Grammatopoulosのコメント、私の以前の回答(下)が間違っていました。セミコロンの位置を固定してコードを実行しようとしましたが、Safariで動作します。

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

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

私の前の不正解する必要があります: のsetTimeoutは一度だけ)(getSecsを呼び出すために起こっています。 、あなたは(おそらく良いアイデア)の上に、後に間隔を停止する場合は

window.setInterval(getSecs,1000); 

:私はあなたが1秒に1回それを呼び出すのではなく、あなたが使用する必要があり、その場合には、一度第二、したいと思いますあなたがちょうどすることができます

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

以降あなたはタイマーを停止したいときに、簡単に呼び出す:

clearInterval(interval); 
+0

'getSecs'は1秒後に自分自身を呼び出し、再び... – GramThanos

+0

ああ、本当です。 Window.setTimeout( 'getSecs()'、1000)の代わりに、window.setTimeout( 'getSecs()'、1000; – thmsdnnr

+0

'clockstart'変数は' initstopwatch'の中ではヌルです。 – GramThanos

0

基本的には、setTimeoutはRでなければなりませんsetIntervalと置き換えられます(getSecsは一度ではなく繰り返し呼び出されます)。次に、それに渡すと予想されるものは、呼び出しではなく関数への参照なので、"getSecs()"ではなく、getSecs(引用符またはカッコはありません)です。それが原因でしょう。私は今コードをテストすることができません。問題は、しかし、それが最大setInterval

になりますようgetSecs()が自分自身を呼び出すべきではないということです第二に、コードは、巨大なクリーンアップに値する誰もが素敵なリファクタリングを思い付くしていない場合、私は明日より多くの助けを提供できるようになります。

+0

私はwebstormを使用しているので、リファクタリングは容易でなければなりません。もし私がその機能をどうするべきか分かっていれば。 – GameCoder

関連する問題