Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

javascript - PHP Timer wait 30 seconds then run a command

I'm just looking for a simple timer, where I can get my page to run a script after 30 seconds.

The idea is that the user has 30 seconds to submit an answer, otherwise the page will run a script and take them to a 'sorry, too slow' style page.

I cannot find the correct php function for this, but it basically we be like:

<?php

Start timer(30);

when timer runs out:
header("location: tooslow.php");
?>

Thanks for any help, Brett

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Store the page request time (from the time() function) in a session variable, then subtract the request time from the submission time (again, from the same function) when the user posts the answer. If the difference is larger than 30, they took too long.

Pseudocode:

<?php
session_start();
$_SESSION['question_start'] = time();
echo "Question: How long is a piece of string?";
...
?>

Then, have that page post to another, which does this:

<?php
session_start();
$time = time() - $_SESSION['question_start'];
if($time > 30)
{
    // fail!
}
...
?>

Of course, if you want the jump to the page to be automatic, you can use the above method in conjunction with one of the JavaScript methods in the other answers here. However, JavaScript alone provides absolutely zero guarantee that the user solved the question within the time limit, as you can just disable JavaScript.

My personal suggestion would be that you don't use a page redirect at all, but instead use Ajax to provide an interactive interface. Essentially, you use a setTimeout call as usual, but when it completes it does an Ajax request to a checking script written in PHP. That script would implement the session timing logic I provided above. If the time is OK, the script increases their score if they got it correct, then responds with the next question, which can be displayed on the page. If the time was too long, it sends back the next question but with a message that they took too long. This allows you to preserve the functionality of back/forward buttons in the browser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...