Javascript计时器帮助

时间:2017-12-12 20:26:22

标签: javascript jquery

我在尝试使用控制台修改一个网站上剩余的时间时遇到了一些问题。

我希望能够将剩余时间设置为零,以便能够进入下一页。

我认为问题在于需要设置多个内容才能进入下一页。

请参阅下面的代码,我们将非常感谢您提供的任何帮助。



var pageLoaded = 0; 
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;

$(document).ready(function() {
    setInterval('AutoSave()', 120000);
    intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);

    if (timerStatus == 'pending') {
    
        var totaltimeclock = document.getElementById('TotalTimeClock');
        if (totaltimeclock != null) {
            document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
        }

        var timeremainingclock = document.getElementById('TimeRemainingClock');
        if (timeremainingclock != null) {
            document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
        }

        StartTimer();
    }

});

function loaded(i,f) {
	if (document.getElementById && document.getElementById(i) != null) 
	{
	    f(); 
	}
	else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}

function SuspendTimer() {
    UpdateBothTimers();
    
    if (timerStatus == 'active') {
        var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
        timerStatus = 'suspended';

        $.ajax({
            type: "POST",
            url: "/Courses/ajax/CourseData.aspx",
            data: data,
            success: displayTime,
            async: false
        });

        clearInterval(intervalIdUpdateBothTimers);
    }
    
}

function AutoSave()
{
    if (timerStatus == 'active')
    {
        SaveTime();
    }
}

function SaveTime()
{
    var data = '';
    if (typeof window.IsScormPage === 'undefined')
    {
        data = "cp=" + this.location.pathname + "&sp=false";
    }
    else
    {
        data = "cp=" + this.location.pathname + "&sp=true";
    }

    data += "&nlg=" + GetNonLinearGuid();

    $.ajax({
		type: "POST",
		url: "/Courses/ajax/CourseData.aspx",
		data: data,
		success: displayTime,
		async: false
	});  
}

function StartTimer()
{
    timerStatus = 'active';

    SetNonLinearGuid();
    SaveTime();
}

// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
    var $nonLinearGuid = $("#nonLinearGuid");

    if ($nonLinearGuid === undefined)
    {
        $nonLinearGuid = $("input[name=nonLinearGuid]");
    }

    if ($nonLinearGuid.length)
    {
        nonLinearGuid = $nonLinearGuid.val() || null;
        window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
    }
}

function GetNonLinearGuid() {
    var nlg = (window.NonLinearGuid || nonLinearGuid),
        admin = getQueryStringByName("admin", parent.window.location.href) || "";

    if (admin.toLowerCase() == "d3v") {
        printNonLinearGuid(nlg);
    }

    return nlg;
}

function getQueryStringByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

function displayTime(result)
{
    
	if (result.isOk == false)
	{
		alert(result.message);
	}
	else
	{	
	    var d = new Date();
        startTicks = d.getTime();
	    
		secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
		secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
		redirectUrl = $(result).find("RedirectUrl").text();

        var suspendTimer = $(result).find("SuspendTimer").text();
        var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
		
		if (redirectUrl != "") {
		    location.href = redirectUrl;
		}
		
	    isError = $(result).find("Error").text();
	    
	    if (isError == "true")
	    {
	        errorCount++;
	        
	        if (errorCount > 3)
	        {
	            logout();
	        }
	    }

	    isOverworked = $(result).find("IsOverworked").text();
	    if (isOverworked == "true") 
	    {
            location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
	    }

	    if (suspendTimer.length > 0) {
	        if ($.trim(suspendTimer).toLowerCase() == "true") {
	            SuspendTimer();
	        }
	    }       
	}
}

function logout()
{
    window.top.location.href = "/Courses/loggedout.aspx";
}

function UpdateBothTimers() {
    
    if (timerStatus != 'active') return;
    
    if (secondsElapsed >= 0)
    {    
        UpdateElapsedTimer();
        //secondsElapsed++;
    }

    if (secondsRemaining >= 0) {
        UpdateRemainingTimer();
    }

    if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
        zeroTimeCounter++;     
        SaveTime();
    }
}
var lang;
function qt(m,lng) {
    
    $('#timeRemaining').css('display', 'none');
    setTimeout("$('#EOMQuiz').submit();", m * 1000);
    lang = lng;
    setTimeout('updateQ('+ m +')', 1000);
}

function updateQ(m) {
   
    --m;
    var text;
    if (lang == 'es') {
        text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
    }
    else {
        text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
    }
   
    if (m > 0) {
       
        setTimeout('updateQ('+m+')', 990);
    }
    else
    {
        $('#eomsubmitDiv').css('background-color', '#FF0000');
       text ='Submitting... Please Wait.';    
    }
   
    if (m <= 10 && m > 0)
    {
        if (m % 2 == 0)
        {
            $('#eomsubmitDiv').css('background-color', '#FFFF00');
        }
        else
        {
            $('#eomsubmitDiv').css('background-color', '#FFFFAA');        
        }
           
    }
    
    $('#eomsubmit').attr('value', text);
}

function UpdateElapsedTimer()
{
    var s = secondsElapsed + (GetTickDiff()/1000);  
    UpdateTimer('TotalTimeClock', s, 'UP');
}

function GetTickDiff()
{
    var d = new Date();
    var tickDiff = d.getTime() - startTicks;
    return tickDiff;
}

function UpdateRemainingTimer()
{
    
    var s = secondsRemaining - (GetTickDiff()/1000);

    estimatedSecondsRemaining = s;
    
    if (s < 0) s = 0;
    
    UpdateTimer('TimeRemainingClock', s, 'DOWN');
}

function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){

    
	//check to see if we can run this code yet
	if(document.getElementById && document.getElementById(ClockID) != null){

		//declare vars
		var _Seconds = 0;
		var _Minutes = 0;
		var _Hours = 0;
		
		//Format Seconds
		_Seconds = Math.floor(ElapsedSeconds % 60);
		if(_Seconds <= 9) {
			_Seconds = "0"+_Seconds;
		}
		
		//Format minutes
		_Minutes = Math.floor(ElapsedSeconds/60 % 60);
		if(_Minutes <= 9) {
			_Minutes = "0"+_Minutes;
		}
		
		//Format hours
		_Hours = Math.floor(ElapsedSeconds/3600 % 60);
		if(_Hours <= 9){
			_Hours = "0"+_Hours;
		}
		
		document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
		
        if (timerStatus != 'active')
        {   
            setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);	
            return;
        }

		if(ElapsedSeconds > 0 || ClockDirection == "UP"){
		
			if(ClockDirection == "UP")
			{
				ElapsedSeconds = ElapsedSeconds + 1;
			}
			else
			{
				ElapsedSeconds = ElapsedSeconds - 1;
			}
			
			//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);			
		}
		else{
			//Timer has hit zero. Lets make sure the next buttons are visible.
			$('#next_top').show();
			$('#next_bot').show();
		}	
	}
	else if(!pageLoaded) //call function again in 100ms
	{
		//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
	}
}	

function DisplayNextButtons(){
	$('#next_top').show();
	$('#next_bot').show();
}

function hideNextButtons(){
	$('#next_top').hide();
	$('#next_bot').hide();
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

我偶然发现了相同的代码。如果你和我在同一个网站上, 我有一个潜在的解决方案。 我没有编辑剩余的时间,而是设置了一个脚本,该脚本将在时间到期时单击下一步。我太懒了,无法检查他们是否正在检查时间戳服务器端。此外,服务器日志看起来更像普通用户。

说明:

  1. 下载适用于Chrome的以下扩展程序 https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija?hl=en
  2. 导航到网站
  3. 点击CJS chrome扩展程序按钮
  4. 选中“为此主机启用cjs”
  5. 将以下JS代码段粘贴到JS框

    var t=setInterval(try_hit_next,1000);
    
    function try_hit_next(){
        if (estimatedSecondsRemaining <= 0)
            window.location = $('#next_top').parent()[0]['href'];
    }
    
  6. 点击保存

答案 1 :(得分:0)

1)无需将“setInterval”分配给变量 t

2)有人试图为此资源制作完全自动化脚本,我的意思是“驾驶防御性课程”,因为它随机地弹出弹出窗口的个人问题,并且还显示带有сourse相关问题的页面(不断相同),所以希望它将是非常有用的“工具”)

答案 2 :(得分:0)

不幸的是,计时器实际上是保存在服务器端的。您可以观察到 CourseData.aspx 的 POST,它将返回 SecondsRemaining 和 SecondsElapsed 的新值。这些新值用于设置客户端计时器。您可以随心所欲地更改客户端变量,但是当您移至下一页时,会再次调用 CourseData.aspx 以获取服务器时间。所以服务器的计时器控制着整个过程。

我相信你看到任何 JS 计时器的唯一原因是为用户提供一个(现在隐藏的)简单的“剩余时间”时钟。

不过我敢打赌,有一种方法可以将新的时间或秒数发布到 CourseData.aspx 页面,我只是不知道这样做可能需要哪些发布数据变量集。